package main import ( "github.com/gorhill/cronexpr" "fmt" "time" ) func main(){ var( expr *cronexpr.Expression err error now time.Time nextTime time.Time ) //if expr,err = cronexpr.Parse("* * * * *");err != nil{ // fmt.Println(err) // return //} //expr = expr if expr,err = cronexpr.Parse("* * * * *");err !=nil{ fmt.Println(err) return } expr = expr now = time.Now() nextTime = expr.Next(now) fmt.Println(now,nextTime) time.AfterFunc(nextTime.Sub(now), func() { fmt.Println("被调度了:",nextTime) }) time.Sleep(50*time.Second) }
2019-08-01 23:00:25.7892266 +0800 CST m=+0.017000401 2019-08-01 23:01:00 +0800 CST 被调度了: 2019-08-01 23:01:00 +0800 CST Process finished with exit code 0
调度多个cron任务
package main import ( "github.com/gorhill/cronexpr" "fmt" "time" ) //代表一个任务 type CronJob struct { expr *cronexpr.Expression nextTime time.Time//expr.Next(Now) } func main(){ //需要有一个调度协程 它定时检查所有的cron任务 谁过期就执行谁 var( expr *cronexpr.Expression now time.Time cronJob *CronJob scheduleTable map[string]*CronJob //key:任务名字 ) scheduleTable = make(map[string]*CronJob) now = time.Now() //1定义两个cronjob expr = cronexpr.MustParse("*/5 * * * * * *") cronJob = &CronJob{ expr:expr, nextTime:expr.Next(now), } scheduleTable["job1"] = cronJob expr = cronexpr.MustParse("*/5 * * * * * *") cronJob = &CronJob{ expr:expr, nextTime:expr.Next(now), } scheduleTable["job2"] = cronJob go func() { var( jobName string cronJob *CronJob now time.Time ) //定时检查一下任务调度表 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) } } //睡眠100毫秒 select { case <-time.NewTimer(100*time.Millisecond).C://1将在100毫秒可读 返回 } } }() time.Sleep(time.Second*100) }
下次执行时间: 2019-08-03 14:44:15 +0800 CST 下次执行时间: 2019-08-03 14:44:15 +0800 CST 执行: job2 执行: job1 下次执行时间: 2019-08-03 14:44:20 +0800 CST 下次执行时间: 2019-08-03 14:44:20 +0800 CST 执行: job2 执行: job1 下次执行时间: 2019-08-03 14:44:25 +0800 CST 下次执行时间: 2019-08-03 14:44:25 +0800 CST 执行: job1 执行: job2 下次执行时间: 2019-08-03 14:44:30 +0800 CST 执行: job1 执行: job2 下次执行时间: 2019-08-03 14:44:30 +0800 CST 下次执行时间: 2019-08-03 14:44:35 +0800 CST 下次执行时间: 2019-08-03 14:44:35 +0800 CST 执行: job1 执行: job2 下次执行时间: 2019-08-03 14:44:40 +0800 CST 执行: job2 下次执行时间: 2019-08-03 14:44:40 +0800 CST 执行: job1
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/11285947.html