Guest User

Untitled

a guest
May 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. (ns timer
  2. (:import [java.util Timer TimerTask]))
  3.  
  4. (def the-timer (Timer.))
  5.  
  6. (defn timer
  7. "Schedules a callback for delayed execution.
  8. Returns a function, that accepts a parameter:
  9. :bump to restart the timer, returning true only if timer was active, hence was extended by that call
  10. :cancel to abort the timer, returning true only if timer was active, hence was canceled b.t.c."
  11. [delay callback]
  12. (let [current (atom 0) ; bump counter, nil is special for a disabled timer
  13. create-task (fn [rev]
  14. (proxy [TimerTask] []
  15. ; only run, when this handler is the latest
  16. (run [] (when (compare-and-set! current rev nil)
  17. (callback)))))
  18.  
  19. ctl (fn [action]
  20. (condp = action
  21. :bump (when-let [in-current @current]
  22. (when (compare-and-set! current in-current (inc in-current))
  23. (.schedule the-timer
  24. (create-task (inc in-current))
  25. (long delay))
  26. true))
  27.  
  28. :cancel (loop [] (when-let [in-cur @current] ; :cancel
  29. (if (compare-and-set! current in-cur nil)
  30. true (recur))))))]
  31. (ctl :bump)
  32. ctl))
Add Comment
Please, Sign In to add comment