summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorsostler <sbostler@gmail.com>2010-04-13 07:26:23 -0400
committersostler <sbostler@gmail.com>2010-04-13 07:26:23 -0400
commit67d043750eb678ab9a2607160e55ef5fa1e070a4 (patch)
tree057c5f98c316f945f45f1703beedb5e39647ad5e /src
parent3bd50c842e97efe87e885c3b28ad270ea390f598 (diff)
Added scheduled-agent
Diffstat (limited to 'src')
-rw-r--r--src/scheduled_agent.clj31
1 files changed, 31 insertions, 0 deletions
diff --git a/src/scheduled_agent.clj b/src/scheduled_agent.clj
new file mode 100644
index 0000000..702b314
--- /dev/null
+++ b/src/scheduled_agent.clj
@@ -0,0 +1,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)