summaryrefslogtreecommitdiff
path: root/timers.go
diff options
context:
space:
mode:
Diffstat (limited to 'timers.go')
-rw-r--r--timers.go72
1 files changed, 58 insertions, 14 deletions
diff --git a/timers.go b/timers.go
index f9fe28608..6a395adac 100644
--- a/timers.go
+++ b/timers.go
@@ -5,6 +5,16 @@ import (
"time"
)
+type Timer struct {
+ Id int32
+ Done bool
+ Cleared bool
+ Interval bool
+ Duration int32 // In milliseconds
+}
+
+var timers = make(map[int32]*Timer)
+
func InitTimers() {
Sub("timers", func(buf []byte) []byte {
msg := &Msg{}
@@ -12,28 +22,62 @@ func InitTimers() {
switch msg.Payload.(type) {
case *Msg_TimerStart:
payload := msg.GetTimerStart()
- return HandleTimerStart(*payload.Id, *payload.Interval,
- *payload.Duration)
+ timers[*payload.Id] = &Timer{
+ Id: *payload.Id,
+ Done: false,
+ Interval: *payload.Interval,
+ Duration: *payload.Duration,
+ Cleared: false,
+ }
+ timers[*payload.Id].StartTimer()
+ return nil
+ case *Msg_TimerClear:
+ payload := msg.GetTimerClear()
+ // TODO maybe need mutex here.
+ timer := timers[*payload.Id]
+ timer.Clear()
+ return nil
default:
panic("[timers] Unexpected message " + string(buf))
}
})
}
-func HandleTimerStart(id int32, interval bool, duration int32) []byte {
+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 wg.Done()
- time.Sleep(time.Duration(duration) * time.Millisecond)
- payload, err := proto.Marshal(&Msg{
- Payload: &Msg_TimerReady{
- TimerReady: &TimerReadyMsg{
- Id: &id,
+ defer t.Clear()
+ for {
+ time.Sleep(time.Duration(t.Duration) * time.Millisecond)
+ if !t.Interval {
+ t.Done = true
+ }
+ pubMsg(&Msg{
+ Payload: &Msg_TimerReady{
+ TimerReady: &TimerReadyMsg{
+ Id: &t.Id,
+ Done: &t.Done,
+ },
},
- },
- })
- check(err)
- Pub("timers", payload)
+ })
+ if t.Done {
+ return
+ }
+ }
}()
- return nil
+}
+
+func pubMsg(msg *Msg) {
+ payload, err := proto.Marshal(msg)
+ check(err)
+ Pub("timers", payload)
}