feudal/worker/clock.go

46 lines
946 B
Go
Raw Permalink Normal View History

2024-05-05 07:11:52 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package worker;
import (
"feudal/message"
"time"
)
// A ticker thread that implements the runner interface and generates tick events for the given context
type Clock struct {
ticker *time.Ticker
quit chan bool
stopped chan bool
}
func NewClock(interval int) *Clock {
return &Clock{ ticker: time.NewTicker(time.Duration(interval) * time.Millisecond), quit: make(chan bool), stopped: make(chan bool) }
}
func (l *Clock) Start(d Dispatcher, c Context) {
go func() {
for {
select {
case tick := <- l.ticker.C:
d.Dispatch(message.New(&message.ClockTick{ T:tick }, c), c)
case <- l.quit:
l.ticker.Stop()
if v := c.Division(); v != nil {
v.Disolve()
}
close(l.stopped)
return
}
}
}()
}
func (l *Clock) Stop() {
close(l.quit)
select {
case <- l.stopped:
}
}