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

创建一个定时任务

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

获得任务的下次执行时间

go
1
nextTime = expr.Next(now)

完整代码

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