Golang 【github.com/robfig/cron】在【Linux】下启动报错【expected exactly 5 fields, found 6: [0/3 * * * * ?]】

起初:

开发环境: 操作系统: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 只能精确到分钟。

参考:https://www.cnblogs.com/liuzhongchao/p/9521897.html

猜想:

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

结果:

测试通过,问题解决。 

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值