Cron常见用法
- 每隔5分钟执行: /5 *
- 第1-5分钟执行5次: 1-5
- 每天10点, 22点整执行一次: 0 10,22 *
开源项目: https://github.com/gorhill/cronexpr
- cronexpr 支持秒粒度 粒度年
parse, err := cronexpr.Parse(
*/5 * * * * * *) // 每5秒func main() {// linux 分钟, 小时, 天, 月, 星期几// cronexpr 支持秒粒度 粒度年parse, err := cronexpr.Parse(`*/5 * * * * * *`)if err == nil {// 下次调度时间next := parse.Next(time.Now())time.AfterFunc(next.Sub(time.Now()), func() {fmt.Println("被调度了...")})}time.Sleep(5 * time.Second)}
调度多个任务
type CronJob struct {expr *cronexpr.ExpressionnextTime time.Time}func main() {scheduleTable := make(map[string]*CronJob)// 执行过期的任务expr := cronexpr.MustParse(`*/5 * * * * * *`)cronJob := &CronJob{expr: expr,nextTime: expr.Next(time.Now()),}scheduleTable["job1"] = cronJobexpr2 := cronexpr.MustParse(`*/5 * * * * * *`)cronJob2 := &CronJob{expr: expr2,nextTime: expr2.Next(time.Now()),}scheduleTable["job2"] = cronJob2go func() {for {now := time.Now()for jobName, cronJob := range scheduleTable {if cronJob.nextTime.Before(now) || cronJob.nextTime.Equal(now) {// 启动一个协程, 执行这个任务go func(jobName string) {fmt.Println("执行: ", jobName)}(jobName)// 计算下一次调度时间cronJob.nextTime = cronJob.expr.Next(now)fmt.Println("下次执行时间: ", cronJob.nextTime)}}select {case <-time.NewTimer(100 * time.Millisecond).C: // 100ms毫秒可读}}}()time.Sleep(100 * time.Second)}
