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

包获取:go get -u github.com/gorhill/cronexpr

创建一个定时任务

1
expr, err = cron.Parse("* * * * *");

获得任务的下次执行时间

1
nextTime = expr.Next(now)

完整代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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的收藏册,转载请著名原文链接~

链接:Go每日一库 - cronexpr

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