// Logger is the interface used in this package for logging, so that any backend // can be plugged in. It is a subset of the github.com/go-logr/logr interface. type Logger interface { // Info logs routine messages about cron's operation. Info(msg string, keysAndValues ...interface{}) // Error logs an error condition. Error(err error, msg string, keysAndValues ...interface{}) }
# Runs at 6am in time.Local cron.New().AddFunc("0 6 * * ?", ...)
# Runs at 6am in America/New_York nyc, _ := time.LoadLocation("America/New_York") c := cron.New(cron.WithLocation(nyc)) c.AddFunc("0 6 * * ?", ...)
// AddFunc adds a func to the Cron to be run on the given schedule. // The spec is parsed using the time zone of this Cron instance as the default. // An opaque ID is returned that can be used to later remove it. func(c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) { return c.AddJob(spec, FuncJob(cmd)) }
// AddJob adds a Job to the Cron to be run on the given schedule. // The spec is parsed using the time zone of this Cron instance as the default. // An opaque ID is returned that can be used to later remove it. func(c *Cron) AddJob(spec string, cmd Job) (EntryID, error) { schedule, err := c.parser.Parse(spec) if err != nil { return0, err } return c.Schedule(schedule, cmd), nil }
// 可以看到需要传入两个参数,`spec` 就是 cron 表达式,Job 类型我们好像还没见过,点进去看 // Job is an interface for submitted cron jobs. type Job interface { Run() }
现在知道我们的定时任务只需要实现 Run() 这个函数就行了,所以我们可以给出自己的 Job 定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
type Job struct { A int`json:"a"` B int`json:"b"` C string`json:"c"` Shut chanint`json:"shut"` }