cronexprLinuxcrontab
1. 实现方式
cronexpr
字段类型 是否为必须字段 允许的值 允许的特殊字符
---------- ---------- -------------- --------------------------
Seconds No 0-59 * / , -
Minutes Yes 0-59 * / , -
Hours Yes 0-23 * / , -
Day of month Yes 1-31 * / , - L W
Month Yes 1-12 or JAN-DEC * / , -
Day of week Yes 0-6 or SUN-SAT * / , - L #
Year No 1970–2099 * / , -
SecondsMinutes
*cron/3-59/15*/...first-last/...,MON,WED,FRI-2000-2010L5LWW15W1WWWLLW##
2. 示例说明
Entry Description Equivalent to
@annually Run once a year at midnight in the morning of January 1 0 0 0 1 1 * *
@yearly Run once a year at midnight in the morning of January 1 0 0 0 1 1 * *
@monthly Run once a month at midnight in the morning of the first of the month 0 0 0 1 * * *
@weekly Run once a week at midnight in the morning of Sunday 0 0 0 * * 0 *
@daily Run once a day at midnight 0 0 0 * * * *
@hourly Run once an hour at the beginning of the hour 0 0 * * * * *
@reboot Not supported
3. 细节说明
* * * * * 20130 * * * * 2013* * * * Mon0 * * * Mon *[0-7][0-6]
4. 安装方式
go get github.com/gorhill/cronexpr
5. 重要函数
5.1 cronexpr.Parse
expr, err := cronexpr.Parse("*/5 * * * * * * ") // 如果表达式解析错误将返回一个错误
5.2 cronexpr.MustParse
expr = cronexpr.MustParse("*/5 * * * * * * ") // 如果表达式解析错误将直接抛出 panic
6. 代码实现
6.1 简单示例
package mainimport ("fmt""time""github.com/gorhill/cronexpr"
)func doTask() {fmt.Println("I am running, time is: ", time.Now())
}
func main() {// 每隔 5 秒执行1次expr, err := cronexpr.Parse("*/5 * * * * * * ") // 如果表达式解析错误将返回一个错误if err != nil {fmt.Println(err)return}nextTime := expr.Next(time.Now())fmt.Println(nextTime)time.AfterFunc(time.Until(nextTime), doTask)time.Sleep(10 * time.Second)}
6.2 监控任务和执行任务处于不同的协程