包获取
go get -u github.com/gorhill/cronexpr
创建一个定时任务
expr, err = cron.Parse("* * * * *");
获得任务的下次执行时间
nextTime = expr.Next(now)
package main import ( "fmt" "time" cron "github.com/gorhill/cronexpr" ) type CronJob struct { expr *cron.Expression nextTime time.Time //expr.now } func main() { var ( cronJob *CronJob expr *cron.Expression now time.Time
scheduleTable map[string]*CronJob // key 任务的名称 ) scheduleTable = make(map[string]*CronJob)
now = time.Now() expr = cron.MustParse("*/5 * * * * * *") cronJob = &CronJob{ expr: expr, nextTime: expr.Next(now), }
scheduleTable["job1"] = cronJob expr = cron.MustParse("*/10 * * * * * *") cronJob = &CronJob{ expr: expr, nextTime: expr.Next(now), } // 将任务注册到调度表中 scheduleTable["job2"] = cronJob // 调度协程 go func() { var( _now time.Time cname string cronjob *CronJob ) for { _now = time.Now() for cname, cronjob = range scheduleTable { if cronjob.nextTime.Before(_now) || cronjob.nextTime.Equal(_now) { go func(name string) { fmt.Println("exec", name) }(cname) cronjob.nextTime = cronjob.expr.Next(_now) fmt.Println("next exec time: ",cronjob.nextTime) } } select { case <-time.NewTimer(100 * time.Millisecond).C: //睡眠 } } }() time.Sleep(time.Minute*3) }