Files
nmon/internal/backup/scheduler.go

69 lines
2.0 KiB
Go

package backup
import (
"context"
"fmt"
"time"
"github.com/v10networks/nmon/internal/clock"
)
// ParseDailyTime parses "HH:MM" (24 hour) into minutes since midnight.
func ParseDailyTime(s string) (time.Duration, error) {
var h, m int
if _, err := fmt.Sscanf(s, "%d:%d", &h, &m); err != nil || h < 0 || h > 23 || m < 0 || m > 59 {
return 0, fmt.Errorf("backup schedule %q: want HH:MM", s)
}
return time.Duration(h)*time.Hour + time.Duration(m)*time.Minute, nil
}
// Scheduler runs a job once a day at a fixed local time (the nightly backup).
type Scheduler struct {
Clock clock.Clock
// At is the time of day in Loc, "HH:MM".
At string
// Loc is the time zone of At; nil means UTC.
Loc *time.Location
// Job is the backup. A failure goes to OnResult and the schedule continues.
Job func(ctx context.Context) error
// OnResult is told after every run; it may be nil.
OnResult func(at time.Time, err error)
}
// NextRun returns the first run strictly after now.
func (s *Scheduler) NextRun(now time.Time) (time.Time, error) {
off, err := ParseDailyTime(s.At)
if err != nil {
return time.Time{}, err
}
loc := s.Loc
if loc == nil {
loc = time.UTC
}
l := now.In(loc)
next := time.Date(l.Year(), l.Month(), l.Day(), int(off/time.Hour), int(off%time.Hour/time.Minute), 0, 0, loc)
if !next.After(now) {
next = time.Date(l.Year(), l.Month(), l.Day()+1, int(off/time.Hour), int(off%time.Hour/time.Minute), 0, 0, loc)
}
return next, nil
}
// Run blocks until ctx ends, running Job at each scheduled time. A DST shift moves the run with the
// wall clock because NextRun is recomputed from the calendar every day.
func (s *Scheduler) Run(ctx context.Context) error {
for {
now := s.Clock.Now()
next, err := s.NextRun(now)
if err != nil {
return err
}
if err := s.Clock.Sleep(ctx, next.Sub(now)); err != nil {
return nil //nolint:nilerr // cancellation is the normal way to stop the scheduler
}
runErr := s.Job(ctx)
if s.OnResult != nil {
s.OnResult(s.Clock.Now(), runErr)
}
}
}