summaryrefslogtreecommitdiff
path: root/src/scheduled_agent.clj
blob: b42bb573986e8548719808d8a3350f42787594b5 (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
32
33
34
35
36
37
(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)
        data  (ref init)
        pfunc (runnable-proxy (fn []
                                (try
                                 (dosync
                                  (ref-set data (func (ensure data))))
                                 (catch Exception e
                                   (print-stack-trace e 5)))))
        future (.scheduleWithFixedDelay pool pfunc 0 period TimeUnit/SECONDS)]
    {:pool   pool
     :data   data
     :future future
     :func   func
     :period period
     :init   init}))

(defn poll [{d :data}]
  "Return current contents of agent."
  @d)

(defn cancel! [{f :future}]
  "Cancel automatic updating of agent data. Cannot be restarted."
  (.cancel f false))

(defn update! [{func :func data :data}]
  "Synchronously update contents of agent."
  (dosync (ref-set data (func (ensure data)))))