Hi, Am 23.08.2011 um 18:01 schrieb Michael Jaaka:
> I have some challenge for you, sine it is easy express it in > imperative language I would like to ask you if is it possible to > create DSL to express such algorithm in clojure or if is it too > complicated just write it in functional manner. The challenge is to > write cron algorithm. I can express it in such way: > http://pastebin.com/1ssvbJ8z Here my try. Basic idea: Provide a sequence of times where things have to run based on a pattern. A pattern is a vector of months, weekdays, days, hours and minutes. Each may be a _ (read: don't care), a number or a set of numbers to specify several allowed times. (One might also want to allow maps for ranges?) The main function then waits till the next scheduled point in time. Executes the function. Wait till the next scheduled point in time. … Much is left to be desired: What if the next moment has already expired when f completes? What does wait-till look like? Maybe cron-seq could be more clever than brute force? But I think you get the idea. Sincerely Meikel (import 'org.joda.time.DateTime) (defn cron-seq [pattern] (let [fix-up-pattern (fn [x] (cond (= x '_) nil (set? x) x :else #{x})) [months weekdays days hours minutes] (map fix-up-pattern pattern)] (for [point-in-time (iterate #(.plusMinutes % 1) (DateTime/now)) :when (or (not minutes) (minutes (.getMinuteOfHour point-in-time))) :when (or (not hours) (hours (.getHourOfDay point-in-time))) :when (or (not days) (days (.getDayOfMonth point-in-time))) :when (or (not weekdays) (weekdays (.getDayOfWeek point-in-time))) :when (or (not months) (months (.getMonthOfYear point-in-time)))] point-in-time))) ; Left as excercise. (defn wait-till [future-point-in-time] (magic happens here)) (defn cron* [pattern f & args] (loop [schedule-time (seq (cron-seq pattern))] (when schedule-time (wait-till (first schedule-time)) (apply f args) (recur (next schedule-time))))) (defmacro cron [pattern & command] `(cron* ~(vec (map #(if (= % '_) `(quote ~%) %) pattern)) ~@command)) ; Usage: (cron [#{1 4 7 10} _ _ 6 30] do-something with arguments) -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to [email protected] Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/clojure?hl=en
