起初:
开发环境: 操作系统:Deepin, Golang 版本:1.12.5
使用 cron,执行定时任务
github.com/robfig/cron
func main() {
c := cron.New()
c.AddFunc("0/3 * * * * ? ", func() {
fmt.Println("a-1: ",time.Now().Format("2006-01-02 15:04:05") )
})
c.Start()
time.Sleep( 1 * time.Minute)
}
问题:
启动的时候,报了一个错误
expected exactly 5 fields, found 6: [0/3 * * * * ?]
表示尴尬,查询资料,发现这么一段话
用过 linux 的应该对 cron 有所了解。linux 中可以通过 crontab -e 来配置定时任务。不过,linux 中的 cron 只能精确到分钟。
猜想:
linux 中的 cron 只能精确到分钟,
而
github.com/robfig/cron
也按照操作系统进行判断,默认支持到分钟级别
测试:
翻阅源码,在cron_test.go
,发现这么一段源码,提供了精确到 秒 级别测试用例
// newWithSeconds returns a Cron with the seconds field enabled.
func newWithSeconds() *Cron {
return New(WithParser(secondParser), WithChain())
}
根据这个提示,修改一下代码,进行测试
// 返回一个支持至 秒 级别的 cron
func newWithSeconds() *cron.Cron {
secondParser := cron.NewParser(cron.Second | cron.Minute |
cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
return cron.New(cron.WithParser(secondParser), cron.WithChain())
}
func main() {
c := cron.newWithSeconds()
c.AddFunc("0/3 * * * * ? ", func() {
fmt.Println("a-1: ",time.Now().Format("2006-01-02 15:04:05") )
})
c.Start()
time.Sleep( 1 * time.Minute)
}
结果:
测试通过,问题解决。