19

我正在寻找一种非常简单的方法来在 Clojure 中定期调用函数。

JavaScriptsetInterval有我想要的那种 API。如果我在 Clojure 中重新构想它,它看起来像这样:

(def job (set-interval my-callback 1000))

; some time later...

(clear-interval job)

出于我的目的,我不介意这是否会创建一个新线程、在线程池中运行或其他什么。时间是否准确也不是关键。事实上,所提供的时间段(以毫秒为单位)可能只是一个呼叫完成结束和下一个呼叫开始之间的延迟。

4

7 回答 7

31

如果你想要很简单

(defn set-interval [callback ms] 
  (future (while true (do (Thread/sleep ms) (callback)))))

(def job (set-interval #(println "hello") 1000))
 =>hello
   hello
   ...

(future-cancel job)
 =>true

再见。

于 2014-01-28T14:00:38.887 回答
23

There's also quite a few scheduling libraries for Clojure: (from simple to very advanced)

Straight from the examples of the github homepage of at-at:

(use 'overtone.at-at)
(def my-pool (mk-pool))
(let [schedule (every 1000 #(println "I am cool!") my-pool)]
  (do stuff while schedule runs)
  (stop schedule))

Use (every 1000 #(println "I am cool!") my-pool :fixed-delay true) if you want a delay of a second between end of task and start of next, instead of between two starts.

于 2014-01-28T12:32:13.690 回答
11

这就是我将如何使用停止通道来完成 core.async 版本。

(defn set-interval
  [f time-in-ms]
  (let [stop (chan)]
    (go-loop []
      (alt!
        (timeout time-in-ms) (do (<! (thread (f)))
                                 (recur))
        stop :stop))
    stop))

以及用法

(def job (set-interval #(println "Howdy") 2000))
; Howdy
; Howdy
(close! job)
于 2015-02-06T16:31:30.647 回答
9

最简单的方法是在单独的线程中设置一个循环。

(defn periodically
  [f interval]
  (doto (Thread.
          #(try
             (while (not (.isInterrupted (Thread/currentThread)))
               (Thread/sleep interval)
               (f))
             (catch InterruptedException _)))
    (.start)))

您可以使用以下命令取消执行Thread.interrupt()

(def t (periodically #(println "Hello!") 1000))
;; prints "Hello!" every second
(.interrupt t)

您甚至可以只使用future来包装循环并future-cancel停止它。

于 2014-01-28T11:24:40.930 回答
8

Another option would be to use java.util.Timer's scheduleAtFixedRate method

edit - multiplex tasks on a single timer, and stop a single task rather than the entire timer

(defn ->timer [] (java.util.Timer.))

(defn fixed-rate 
  ([f per] (fixed-rate f (->timer) 0 per))
  ([f timer per] (fixed-rate f timer 0 per))
  ([f timer dlay per] 
    (let [tt (proxy [java.util.TimerTask] [] (run [] (f)))]
      (.scheduleAtFixedRate timer tt dlay per)
      #(.cancel tt))))

;; Example
(let [t    (->timer)
      job1 (fixed-rate #(println "A") t 1000)
      job2 (fixed-rate #(println "B") t 2000)
      job3 (fixed-rate #(println "C") t 3000)]
  (Thread/sleep 10000)
  (job3) ;; stop printing C
  (Thread/sleep 10000)
  (job2) ;; stop printing B
  (Thread/sleep 10000)
  (job1))
于 2014-01-28T12:31:53.533 回答
8

我尝试对此进行编码,其界面比原始问题中指定的稍有修改。这就是我想出的。

(defn periodically [fn millis]
  "Calls fn every millis. Returns a function that stops the loop."
  (let [p (promise)]
    (future
      (while
          (= (deref p millis "timeout") "timeout")
        (fn)))
    #(deliver p "cancel")))

欢迎反馈。

于 2014-01-28T11:38:26.223 回答
4

使用core.async

(ns your-namespace
 (:require [clojure.core.async :as async :refer [<! timeout chan go]])
 )

(def milisecs-to-wait 1000)
(defn what-you-want-to-do []
  (println "working"))

(def the-condition (atom true))

(defn evaluate-condition []
  @the-condition)

(defn stop-periodic-function []
  (reset! the-condition false )
  )

(go
 (while (evaluate-condition)
   (<! (timeout milisecs-to-wait))
   (what-you-want-to-do)))
于 2014-01-28T11:59:11.020 回答