在clojure中实现cron类型的调度程序

zca*_*ate 9 clojure

我正在寻找任何可以在给定时间触发事件的方法,

例如:我希望特定的流程在上午9:30开始,然后我可以触发另一个流程,半小时后开始运行等.

提前致谢!


更新2:

感谢@亚瑟- ulfeoldt和@未知的人谁也使用建议https://github.com/samaaron/at-at删除他的答案之前.文档有点过时,但这是我的方式.

(use 'overtone.at-at)

(def my-pool (mk-pool))
;=> make a thread pool

(every 1000 #(println "I am super cool!") my-pool :initial-delay 2000) 
;=> starts print function every 1 sec after a 2 sec delay

(stop *1) 
;=> stops it

所以为了让它从正好9开始,间隔半小时,我会做:

(require '[clj-time.core :as t])
(require '[clj-time.coerce :as c])
(use 'overtone.at-at)

;Make Thread Pool
(def my-pool (mk-pool))

(def current-time (t/now))

(def current-date (t/date-time 
                    (t/year current-time)
                    (t/month current-time)
                    (t/day current-time)))

(def next-9-oclock
  (if (> 9 (t/hour current-time))
    (t/plus current-date (t/hours 9))
    (t/plus current-date (t/days 1) (t/hours 9))))

(def initial-delay
   (- (c/to-long next-9-oclock) (c/to-long current-time))

(every 1800000 
       #(println "I am super cool!") 
       my-pool 
       :initial-delay 
       initial-delay) 

更新:

@ arthur-ulfeoldt,我不知道如何将一些java代码翻译成clojure. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html

喜欢:

final ScheduledFuture<?> beeperHandle = 
        scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
Run Code Online (Sandbox Code Playgroud)

和:

final Runnable beeper = new Runnable() {
        public void run() { System.out.println("beep"); }
     };
Run Code Online (Sandbox Code Playgroud)

整个例子

 class BeeperControl {
    private final ScheduledExecutorService scheduler = 
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture beeperHandle = 
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }

zca*_*ate 10

我需要一些东西

  • 以整秒间隔开始计划任务,而不是具有高系统时间精度的整个分钟间隔.
  • 会根据需要生成尽可能多的线程,因此在较早的时间间隔内启动的任务可能会在以后的时间间隔开始执行.

在为at-at,Monotony和Quartzite做了一些源代码阅读之后,我觉得它们不符合我所追求的要求(这真的是更为光明的东西)所以我写了自己的 - cronj

用法示例.

(require '[cronj.core :as cj])

(cj/schedule-task! {:id 0   :desc 0 
              :handler #(println "job 0:" %) 
              :tab "/5 * * * * * *"}) ;; every 5 seconds
(cj/schedule-task! {:id 1   :desc 1 
              :handler #(println "job 1:" %) 
              :tab "/3 * * * * * *"}) ;; every 3 seconds

(cj/start!) 

;; wait for scheduler to do its thing ......

(cj/stop!)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你这个图书馆. (2认同)