forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timers.go
79 lines (73 loc) · 1.38 KB
/
timers.go
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
77
78
79
// Copyright 2018 Ryan Dahl <ry@tinyclouds.org>
// All rights reserved. MIT License.
package deno
import (
"github.com/golang/protobuf/proto"
"time"
)
type Timer struct {
Id int32
Done bool
Cleared bool
Interval bool
Delay int32 // In milliseconds
}
var timers = make(map[int32]*Timer)
func InitTimers() {
Sub("timers", func(buf []byte) []byte {
msg := &Msg{}
check(proto.Unmarshal(buf, msg))
switch msg.Command {
case Msg_TIMER_START:
id := msg.TimerStartId
t := &Timer{
Id: id,
Done: false,
Interval: msg.TimerStartInterval,
Delay: msg.TimerStartDelay,
Cleared: false,
}
if t.Delay < 10 {
t.Delay = 10
}
t.StartTimer()
timers[id] = t
return nil
case Msg_TIMER_CLEAR:
// TODO maybe need mutex here.
timer := timers[msg.TimerClearId]
timer.Clear()
default:
panic("[timers] Unexpected message " + string(buf))
}
return nil
})
}
func (t *Timer) Clear() {
if !t.Cleared {
wg.Done()
t.Cleared = true
delete(timers, t.Id)
}
t.Done = true
}
func (t *Timer) StartTimer() {
wg.Add(1)
go func() {
defer t.Clear()
for {
time.Sleep(time.Duration(t.Delay) * time.Millisecond)
if !t.Interval {
t.Done = true
}
PubMsg("timers", &Msg{
Command: Msg_TIMER_READY,
TimerReadyId: t.Id,
TimerReadyDone: t.Done,
})
if t.Done {
return
}
}
}()
}