feudal/worker/clock.go
Matthew Rich 1b9d1b1fb1
Some checks failed
Declarative Tests / test (push) Waiting to run
Lint / golangci-lint (push) Has been cancelled
add context
2024-05-05 00:11:52 -07:00

46 lines
946 B
Go

// 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:
}
}