-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.rkt
76 lines (58 loc) · 1.77 KB
/
timer.rkt
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#lang racket
(require racket/date
(rename-in web-server/private/timer
[start-timer-manager start-timeout-manager]
[start-timer start-timeout]
[cancel-timer! cancel-timeout!]))
(provide timer%
repeat-timer%
set-timeout
cancel-timeout!)
(define timeout-manager (start-timeout-manager))
(define (set-timeout callback seconds)
(start-timeout timeout-manager seconds callback))
(define repeat-timer%
(class object%
(super-new)
(init-field on-repeat times seconds [on-end #f])
(define current 0)
(define timeout #f)
(define/public (start)
(when (not timeout)
(set! current 0)
(set-timeout)))
(define/public (cancel)
(when timeout
(cancel-timeout! timeout)
(set! timeout #f)
(set! current times)))
(define (set-timeout)
(set! timeout
(start-timeout timeout-manager
seconds
handle-repeat)))
(define (handle-repeat)
(cond
[(< current times)
(set! current (+ current 1))
(on-repeat current)
(set-timeout)]
[on-end (on-end)]))))
(define timer%
(class object%
(super-new)
(init-field time on-timeout)
(define timeout #f)
(define/public (start)
(when (not timeout)
(define timeout-seconds (- time (date->seconds (current-date))))
(define (timeout-callback)
(set! timeout #f)
(on-timeout))
(if (<= timeout-seconds 0)
(timeout-callback)
(set! timeout (set-timeout timeout-callback timeout-seconds)))))
(define/public (stop)
(when timeout
(cancel-timeout! timeout)
(set! timeout #f)))))