sojuboy/internal/scheduler/scheduler.go

32 lines
680 B
Go
Raw Normal View History

package scheduler
import (
"context"
"log"
"time"
"github.com/robfig/cron/v3"
)
// Start runs the cron scheduler until ctx is done.
func Start(ctx context.Context, spec string, job func(now time.Time), logger *log.Logger) error {
c := cron.New(cron.WithParser(cron.NewParser(cron.SecondOptional|cron.Minute|cron.Hour|cron.Dom|cron.Month|cron.Dow|cron.Descriptor)))
_, err := c.AddFunc(spec, func() {
job(time.Now())
})
if err != nil {
return err
}
if logger != nil {
logger.Printf("scheduler started: %s", spec)
}
c.Start()
go func() {
<-ctx.Done()
c.Stop()
}()
return nil
}