-
Notifications
You must be signed in to change notification settings - Fork 30
/
timer.html
47 lines (43 loc) · 1.73 KB
/
timer.html
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
38
39
40
41
42
43
44
45
46
47
---
layout: doc
title: Timer facility
---
<h2 id="timer">Timer facility</h2>
{% highlight clojure %}
(:require [org.httpkit.timer :as timer])
{% endhighlight %}
<p>A general purpose, efficient timer is provided. </p>
<h3 class="anchor" id="schedule">schedule-task</h3>
<p>
schedules body for invocation after given time and returns a
CancelableFutureTask. <code>(cancel task)</code> will cancel the task if possible and
return true iff cancellation was successful.
</p>
{% highlight clojure %}
(let [task (timer/schedule-task 1000
(println "This will print in 1000ms if not canceled"))]
(Thread/sleep (rand-nth [1100 900]))
(if (timer/cancel task)
(println "Task was cancelled")
(println "Task already executed"))){% endhighlight %}
<h3 class="anchor" id="timeout">with-timeout</h3>
<p>
schedules timeout-form for invocation after given timeout and wraps named
fn so that calling it with any arguments also cancels the timeout if possible.
If the timeout has already been invoked, the fn will not run and will
immediately return nil
</p>
{% highlight clojure %}
(with-timeout println 800 (println "Timeout task triggered")
(Thread/sleep (rand-nth [900 700]))
(println "Timeout task was cancelled"))
(defn handler [req]
(with-channel req channel
(with-timeout send! 1000
(send! {:status 200 :body "service did not return in 1000ms"})
(let [result (call-a-long-running-service)]
;; Call `send!` cancels the timeout if possible.
;; If the timeout has already been invoked (the service takes more than 1000ms to return),
;; `send!` will not run and return nil immediately.
(send! {:status 200 :body result})))))
{% endhighlight %}