summaryrefslogtreecommitdiff
path: root/timers.go
blob: f9fe28608e834b52ff431173e72740f3fb0f5c4e (plain)
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
package main

import (
	"github.com/golang/protobuf/proto"
	"time"
)

func InitTimers() {
	Sub("timers", func(buf []byte) []byte {
		msg := &Msg{}
		check(proto.Unmarshal(buf, msg))
		switch msg.Payload.(type) {
		case *Msg_TimerStart:
			payload := msg.GetTimerStart()
			return HandleTimerStart(*payload.Id, *payload.Interval,
				*payload.Duration)
		default:
			panic("[timers] Unexpected message " + string(buf))
		}
	})
}

func HandleTimerStart(id int32, interval bool, duration int32) []byte {
	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,
				},
			},
		})
		check(err)
		Pub("timers", payload)
	}()
	return nil
}