Adds simple workers start/stop methods

This commit is contained in:
Miguel de la Cruz 2023-07-01 17:23:19 +02:00
parent b90e3afc76
commit e3fcf6adf1
4 changed files with 77 additions and 1 deletions

View file

@ -10,3 +10,6 @@ test-watch:
fmt: fmt:
go fmt ./... go fmt ./...
run:
go run ./cmd/birthdaybot -config example-config.yml

View file

@ -3,6 +3,7 @@ package main
import ( import (
"flag" "flag"
"os" "os"
"time"
"git.ctrlz.es/mgdelacroix/birthdaybot/model" "git.ctrlz.es/mgdelacroix/birthdaybot/model"
"git.ctrlz.es/mgdelacroix/birthdaybot/server" "git.ctrlz.es/mgdelacroix/birthdaybot/server"
@ -19,9 +20,15 @@ func main() {
os.Exit(1) os.Exit(1)
} }
_, err = server.New(config) srv, err := server.New(config)
if err != nil { if err != nil {
log.Error("error creating server", "error", err) log.Error("error creating server", "error", err)
os.Exit(1) os.Exit(1)
} }
srv.Start()
time.Sleep(5 * time.Second)
srv.Stop()
} }

View file

@ -12,6 +12,7 @@ import (
type Server struct { type Server struct {
logger *log.Logger logger *log.Logger
config *model.Config config *model.Config
workers []*Worker
birthdays []*model.Birthday birthdays []*model.Birthday
} }
@ -32,7 +33,24 @@ func New(config *model.Config) (*Server, error) {
logger: logger, logger: logger,
config: config, config: config,
birthdays: birthdays, birthdays: birthdays,
workers: []*Worker{NewWorker(logger)},
} }
return server, nil return server, nil
} }
func (s *Server) Start() {
s.logger.Info("starting server")
for _, worker := range s.workers {
worker.Start()
}
s.logger.Info("server started", "workers", len(s.workers))
}
func (s *Server) Stop() {
s.logger.Info("stopping server")
for _, worker := range s.workers {
worker.Stop()
}
s.logger.Info("server stopped", "workers", len(s.workers))
}

48
server/worker.go Normal file
View file

@ -0,0 +1,48 @@
package server
import (
"time"
"github.com/charmbracelet/log"
)
type Worker struct {
logger *log.Logger
stop chan bool
stopped chan bool
}
func NewWorker(logger *log.Logger) *Worker {
return &Worker{
logger: logger,
stop: make(chan bool, 1),
stopped: make(chan bool, 1),
}
}
func (w *Worker) Start() {
w.logger.Info("starting worker")
go w.run()
w.logger.Info("worker started")
}
func (w *Worker) Stop() {
w.logger.Info("stopping worker")
w.stop <- true
<-w.stopped
w.logger.Info("worker stopped")
}
func (w *Worker) run() {
ticker := time.NewTicker(1 * time.Second)
for {
select {
case t := <-ticker.C:
w.logger.Info("ticker ticked for worker", "tick", t)
case <-w.stop:
w.logger.Info("received stop signal")
w.stopped <- true
return
}
}
}