2018-05-28 21:50:44 -04:00
|
|
|
// Copyright 2018 Ryan Dahl <ry@tinyclouds.org>
|
|
|
|
// All rights reserved. MIT License.
|
2018-05-29 04:28:32 -04:00
|
|
|
package deno
|
2018-05-21 23:00:36 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/golang/protobuf/proto"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2018-05-23 14:53:41 -04:00
|
|
|
type Timer struct {
|
|
|
|
Id int32
|
|
|
|
Done bool
|
|
|
|
Cleared bool
|
|
|
|
Interval bool
|
2018-05-31 14:26:43 -04:00
|
|
|
Delay int32 // In milliseconds
|
2018-05-23 14:53:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
var timers = make(map[int32]*Timer)
|
|
|
|
|
2018-05-21 23:00:36 -04:00
|
|
|
func InitTimers() {
|
|
|
|
Sub("timers", func(buf []byte) []byte {
|
|
|
|
msg := &Msg{}
|
|
|
|
check(proto.Unmarshal(buf, msg))
|
2018-05-25 15:36:13 -04:00
|
|
|
switch msg.Command {
|
|
|
|
case Msg_TIMER_START:
|
|
|
|
id := msg.TimerStartId
|
|
|
|
t := &Timer{
|
|
|
|
Id: id,
|
2018-05-23 14:53:41 -04:00
|
|
|
Done: false,
|
2018-05-25 15:36:13 -04:00
|
|
|
Interval: msg.TimerStartInterval,
|
2018-05-31 14:26:43 -04:00
|
|
|
Delay: msg.TimerStartDelay,
|
2018-05-23 14:53:41 -04:00
|
|
|
Cleared: false,
|
|
|
|
}
|
2018-05-31 14:26:43 -04:00
|
|
|
if t.Delay < 10 {
|
|
|
|
t.Delay = 10
|
2018-05-31 11:28:14 -04:00
|
|
|
}
|
2018-05-25 15:36:13 -04:00
|
|
|
t.StartTimer()
|
|
|
|
timers[id] = t
|
2018-05-23 14:53:41 -04:00
|
|
|
return nil
|
2018-05-25 15:36:13 -04:00
|
|
|
case Msg_TIMER_CLEAR:
|
2018-05-23 14:53:41 -04:00
|
|
|
// TODO maybe need mutex here.
|
2018-05-25 15:36:13 -04:00
|
|
|
timer := timers[msg.TimerClearId]
|
2018-05-23 14:53:41 -04:00
|
|
|
timer.Clear()
|
2018-05-21 23:00:36 -04:00
|
|
|
default:
|
|
|
|
panic("[timers] Unexpected message " + string(buf))
|
|
|
|
}
|
2018-05-25 15:36:13 -04:00
|
|
|
return nil
|
2018-05-21 23:00:36 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-05-23 14:53:41 -04:00
|
|
|
func (t *Timer) Clear() {
|
|
|
|
if !t.Cleared {
|
|
|
|
wg.Done()
|
|
|
|
t.Cleared = true
|
|
|
|
delete(timers, t.Id)
|
|
|
|
}
|
|
|
|
t.Done = true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timer) StartTimer() {
|
2018-05-21 23:00:36 -04:00
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
2018-05-23 14:53:41 -04:00
|
|
|
defer t.Clear()
|
|
|
|
for {
|
2018-05-31 14:26:43 -04:00
|
|
|
time.Sleep(time.Duration(t.Delay) * time.Millisecond)
|
2018-05-23 14:53:41 -04:00
|
|
|
if !t.Interval {
|
|
|
|
t.Done = true
|
|
|
|
}
|
2018-05-23 17:23:50 -04:00
|
|
|
PubMsg("timers", &Msg{
|
2018-05-25 15:36:13 -04:00
|
|
|
Command: Msg_TIMER_READY,
|
|
|
|
TimerReadyId: t.Id,
|
|
|
|
TimerReadyDone: t.Done,
|
2018-05-23 14:53:41 -04:00
|
|
|
})
|
|
|
|
if t.Done {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2018-05-21 23:00:36 -04:00
|
|
|
}()
|
2018-05-23 14:53:41 -04:00
|
|
|
}
|