summaryrefslogtreecommitdiff
path: root/src/scheduled_agent.clj
diff options
context:
space:
mode:
authordumpfmprod <dumpfmprod@ubuntu.(none)>2010-04-13 07:31:11 -0400
committerdumpfmprod <dumpfmprod@ubuntu.(none)>2010-04-13 07:31:11 -0400
commit41661c78d6941a4a63bebbb30cf0bcf82aa04138 (patch)
treec2c5607e48640f86acf29b1a744d43cdd7e05527 /src/scheduled_agent.clj
parentd87cbb95e22bae4597943b9a39f938fd5bda4253 (diff)
parentd0bd678ff36fed7cf492b89542588b82efafb938 (diff)
Merge branch 'master' of /pichat/repo
Diffstat (limited to 'src/scheduled_agent.clj')
-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)