X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/150d707b16a5495272dfb02d690d99bfae50c14e..77f29e78734dc16cfcea5f41b8e0185f8b33534a:/schedule.go?ds=sidebyside diff --git a/schedule.go b/schedule.go index 9b95ce7..5da024d 100644 --- a/schedule.go +++ b/schedule.go @@ -6,7 +6,7 @@ import ( "encoding/json" "errors" "fmt" - "log" + "log/slog" "os" "slices" "strconv" @@ -51,7 +51,7 @@ const ( // openSchedules reads the schedules of the file at path. A missing file holds // none. The clock gives the time and the time zone of the schedules, and logger // gets one line for each run. -func openSchedules(path string, clock func() time.Time, logger *log.Logger) (*Schedules, error) { +func openSchedules(path string, clock func() time.Time, logger *slog.Logger) (*Schedules, error) { s := &Schedules{ path: path, clock: clock, @@ -96,7 +96,7 @@ func openSchedules(path string, clock func() time.Time, logger *log.Logger) (*Sc type Schedules struct { path string clock func() time.Time - logger *log.Logger + logger *slog.Logger check time.Duration changed chan struct{} @@ -115,8 +115,11 @@ func (s *Schedules) Run(ctx context.Context, l *TurnLoop) error { return err } - var timer *time.Timer - var timeout <-chan time.Time + var ( + timer *time.Timer + timeout <-chan time.Time + ) + wait, found := s.Wait(s.clock()) if found { timer = time.NewTimer(min(wait, s.check)) @@ -253,7 +256,9 @@ func (s *Schedules) Remove(id int) (string, error) { // text of the schedule. func (s *Schedules) deliver(ctx context.Context, l *TurnLoop) error { now := s.clock() + var turns []Message + for _, schedule := range s.Due(now) { message, err := l.Work(scheduleSource, schedule.Message(now), "") if err != nil { @@ -276,12 +281,13 @@ func (s *Schedules) deliver(ctx context.Context, l *TurnLoop) error { return err } + attrs := []any{"id", schedule.ID} if schedule.late(now) { - s.logger.Printf("schedule %d runs %s late, because the daemon was stopped at its time", schedule.ID, durationText(now.Sub(schedule.Due))) - } else { - s.logger.Printf("schedule %d runs", schedule.ID) + attrs = append(attrs, "late", now.Sub(schedule.Due)) } + s.logger.Info("schedule ran", attrs...) + turns = append(turns, message) } @@ -293,6 +299,7 @@ func (s *Schedules) deliver(ctx context.Context, l *TurnLoop) error { // Due returns the schedules whose time is not after now, by due time. func (s *Schedules) Due(now time.Time) []Schedule { var due []Schedule + for _, schedule := range s.sorted() { if !schedule.Due.After(now) { due = append(due, schedule) @@ -363,6 +370,7 @@ func (s *Schedules) change() { // sorted returns a copy of the schedules by due time, then by ID. func (s *Schedules) sorted() []Schedule { s.mutex.Lock() + schedules := slices.Clone(s.file.Schedules) s.mutex.Unlock()