summaryrefslogtreecommitdiff
path: root/src/scheduled_agent.clj
blob: 702b314b6075b04e6ff6ad0a55bdd977045e0bf4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(ns scheduled-agent
  (:import java.util.concurrent.Executors
           java.util.concurrent.TimeUnit)
  (:use clojure.stacktrace))

(defn- runnable-proxy [f]
  (proxy [Runnable] [] (run [] (f))))

(defn scheduled-agent
  [func period init]
  (let [pool  (Executors/newScheduledThreadPool 1)
        r     (ref init)
        pfunc (runnable-proxy (fn []
                                (try
                                 (dosync
                                  (ref-set r (func (ensure r))))
                                 (catch Exception e
                                   (print-stack-trace e 5)))))
        future (.scheduleWithFixedDelay pool pfunc 0 period TimeUnit/SECONDS)]
    {:pool pool
     :data r
     :future future
     :func pfunc
     :period period
     :init init}))

(defn cancel [{f :future}]
  (.cancel f false))

(defn poll [{d :data}]
  @d)