Skip to content

Instantly share code, notes, and snippets.

@hiredman
Created August 31, 2009 08:06
Show Gist options
  • Save hiredman/178350 to your computer and use it in GitHub Desktop.
Save hiredman/178350 to your computer and use it in GitHub Desktop.
(ns hiredman.schedule
(:import (java.util.concurrent ScheduledThreadPoolExecutor TimeUnit)))
(def unit {:minutes TimeUnit/MINUTES :seconds TimeUnit/SECONDS :hours TimeUnit/HOURS})
(def tasks (ref {}))
(def #^{:doc "ScheduledThreadPoolExecutor for scheduling repeated/delayed tasks"}
task-runner (ScheduledThreadPoolExecutor. (+ 1 (.availableProcessors (Runtime/getRuntime)))))
(defn fixedrate
([{:keys [name task start-delay rate unit]}]
(fixedrate name task start-delay rate unit))
([name task t1 t2 tu]
(let [ft (.scheduleAtFixedRate task-runner #^Callable task (long t1) (long t2) tu)]
(dosync (alter tasks assoc name ft)))))
(defn cancel [name]
(.cancel (get @tasks name) true)
(dosync
(alter tasks dissoc name)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment