From 3b09a7da10a76409cbc90b0133ded85a07921e72 Mon Sep 17 00:00:00 2001 From: Miguel de la Cruz Date: Mon, 10 Jul 2023 10:16:36 +0200 Subject: [PATCH] Add initial simple approach to time loop --- server/worker.go | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/server/worker.go b/server/worker.go index 20ec18c..5b66c54 100644 --- a/server/worker.go +++ b/server/worker.go @@ -3,6 +3,7 @@ package server import ( "time" + "git.ctrlz.es/mgdelacroix/birthdaybot/model" "github.com/charmbracelet/log" ) @@ -35,15 +36,45 @@ func (w *Worker) Stop() { w.logger.Info("worker stopped") } +func (w *Worker) notifyDay(year, month, day int) { + birthdays := model.FilterByDate(w.server.Birthdays(), year, month, day) + w.logger.Info("notifying for date", "birthdays", len(birthdays), "year", year, "month", month, "day", day) + + for _, b := range birthdays { + w.logger.Info("notifying for birthday", "name", b.Name) + w.server.Notify(b) + } +} + func (w *Worker) run() { - ticker := time.NewTicker(1 * time.Second) + // first we calculate the delta with 23:00 + now := time.Now() + eleven := time.Date(now.Year(), now.Month(), now.Day(), 23, 0, 0, 0, now.Location()) + + if eleven.Before(now) { + // tomorrow at 23:00 + eleven = time.Date(now.Year(), now.Month(), now.Day()+1, 23, 0, 0, 0, now.Location()) + } + + firstTick := eleven.Sub(now) + + var ticker *time.Ticker + w.logger.Info("first timer tick set", "tick", firstTick) + select { + case <-time.After(firstTick): + ticker = time.NewTicker(24 * time.Hour) + w.notifyDay(eleven.Year(), int(eleven.Month()), eleven.Day()) + case <-w.stop: + w.logger.Info("received stop signal") + w.stopped <- true + return + } + for { select { case t := <-ticker.C: w.logger.Info("ticker ticked for worker", "tick", t) - // ToDo: improve logic here - b := w.server.Birthdays()[0] - w.server.Notify(b) + w.notifyDay(t.Year(), int(t.Month()), t.Day()) case <-w.stop: w.logger.Info("received stop signal") w.stopped <- true