golang cronexpr定时任务包使用

包获取

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) }

  

 

转载于:https://www.cnblogs.com/LC161616/p/10380636.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值