Routine manager now manages functions

This commit is contained in:
Sasha Koshka 2023-05-26 13:06:21 -04:00
parent b17bad32fe
commit 23f7497622

View File

@ -6,12 +6,9 @@ import "log"
import "time" import "time"
import "sync" import "sync"
// Routine represents an object that can be run. // Routine is a long-running function that does not return until it is finished.
type Routine interface { // An error is returned if the routine exited due to an error.
// Run starts the routine and does not return until it is finished. An type Routine func () error
// error is returned if the routine exited due to an error.
Run () error
}
// Manager is a system capable of managing multiple routines, and restarting // Manager is a system capable of managing multiple routines, and restarting
// them if they fail. // them if they fail.
@ -49,6 +46,12 @@ func (manager *Manager) Run () error {
return errExit return errExit
} }
// Append adds one or more routines to the Routines slice. This has no effect if
// the manager is already running.
func (manager *Manager) Append (routines ...Routine) {
manager.Routines = append(manager.Routines, routines...)
}
func (manager *Manager) log (message ...any) { func (manager *Manager) log (message ...any) {
if manager.Logger == nil { if manager.Logger == nil {
log.Println(message...) log.Println(message...)
@ -64,7 +67,7 @@ func (manager *Manager) runRoutine (routine Routine, group *sync.WaitGroup, errE
for { for {
// TODO: recover from panics // TODO: recover from panics
lastStart := time.Now() lastStart := time.Now()
err = routine.Run() err = routine()
if err == nil { if err == nil {
manager.log("(i) routine exited") manager.log("(i) routine exited")