本文发布于Cylon的收藏册,转载请著名原文链接~


包获取: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)
}

本文发布于Cylon的收藏册,转载请著名原文链接~

链接:https://www.oomkill.com/2019/02/cronexpr/

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」 许可协议进行许可。