From e3fcf6adf18eabf1c1a75f073c945d8285741350 Mon Sep 17 00:00:00 2001 From: Miguel de la Cruz Date: Sat, 1 Jul 2023 17:23:19 +0200 Subject: [PATCH] Adds simple workers start/stop methods --- Makefile | 3 +++ cmd/birthdaybot/main.go | 9 +++++++- server/server.go | 18 ++++++++++++++++ server/worker.go | 48 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 server/worker.go diff --git a/Makefile b/Makefile index ae03b1b..7e4f452 100644 --- a/Makefile +++ b/Makefile @@ -10,3 +10,6 @@ test-watch: fmt: go fmt ./... + +run: + go run ./cmd/birthdaybot -config example-config.yml diff --git a/cmd/birthdaybot/main.go b/cmd/birthdaybot/main.go index 6860f40..9bbebe6 100644 --- a/cmd/birthdaybot/main.go +++ b/cmd/birthdaybot/main.go @@ -3,6 +3,7 @@ package main import ( "flag" "os" + "time" "git.ctrlz.es/mgdelacroix/birthdaybot/model" "git.ctrlz.es/mgdelacroix/birthdaybot/server" @@ -19,9 +20,15 @@ func main() { os.Exit(1) } - _, err = server.New(config) + srv, err := server.New(config) if err != nil { log.Error("error creating server", "error", err) os.Exit(1) } + + srv.Start() + + time.Sleep(5 * time.Second) + + srv.Stop() } diff --git a/server/server.go b/server/server.go index f27846a..9da5414 100644 --- a/server/server.go +++ b/server/server.go @@ -12,6 +12,7 @@ import ( type Server struct { logger *log.Logger config *model.Config + workers []*Worker birthdays []*model.Birthday } @@ -32,7 +33,24 @@ func New(config *model.Config) (*Server, error) { logger: logger, config: config, birthdays: birthdays, + workers: []*Worker{NewWorker(logger)}, } 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)) +} diff --git a/server/worker.go b/server/worker.go new file mode 100644 index 0000000..805f86c --- /dev/null +++ b/server/worker.go @@ -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 + } + } +}