这个Go开源工具有点意思

Go语言精选

共 3790字,需浏览 8分钟

 · 2021-04-11

作为程序员,特别是后端,应该离不开定时任务,所以 CRON 表达式少不了。但你可能有这样的烦恼:

  • Linux 的 Cron 是 5 或 6 位的,而 Go 库中的是 7 位的(支持到秒);
  • 一个 CRON 表达式,看不懂是啥意思;比如 0 23 ? * MON-FRI 你知道是什么意思吗?

如果有一个工具或库,能够将这个表达式转为人类可读的方式,这样非技术人员也可以看懂了。

今天还真发现一个,使用 Go 语言实现的。

项目地址:https://github.com/lnquy/cron,它可以作为单独的工具使用,也可以作为库集成到你的程序中。

不过这个不是原创,是借鉴 C# 库 https://github.com/bradymholt/cron-expression-descriptor 和 JavaScript 库 https://github.com/bradymholt/cRonstrue。

这个库强大的地方在于支持全球 26 种语言。比如文章开头的表达式,转换后如下:

$ hcron -locale zh_CN "0 23 ? * MON-FRI"
0 23 ? * MON-FRI: 在下午 11:00, 星期一至星期五

安装

马上 2021 年了,请使用 Go Module。

$ go get -v github.com/lnquy/cron/...

使用

作为库使用

官方给了一个例子:

// Init with default EN locale
exprDesc, _ := cron.NewDescriptor()

desc, _ := exprDesc.ToDescription("* * * * *", cron.Locale_en)
// "Every minute" 

desc, _ := exprDesc.ToDescription("0 23 ? * MON-FRI", cron.Locale_en)
// "At 11:00 PM, Monday through Friday" 

desc, _ := exprDesc.ToDescription("23 14 * * SUN#2", cron.Locale_en)
// "At 02:23 PM, on the second Sunday of the month"

// Init with custom configs
exprDesc, _ := cron.NewDescriptor(
    cron.Use24HourTimeFormat(true),
    cron.DayOfWeekStartsAtOne(true),
    cron.Verbose(true),
    cron.SetLogger(log.New(os.Stdout, "cron: "0)),
    cron.SetLocales(cron.Locale_en, cron.Locale_fr),
)

更多例子可以在这里找到:https://github.com/lnquy/cron/tree/develop/examples。

作为工具使用

上面 go get 命令会将 hcron 这个命令安装到 $GOBIN(默认是 $GOPATH/bin),建议将该目录放到 $PATH 中,方便直接使用。

$ hcron -h
hcron converts the CRON expression to human readable description.

Usage:
  hcron [flags] [cron expression]

Flags:
  -24-hour
     Output description in 24 hour time format
  -dow-starts-at-one
     Is day of the week starts at 1 (Monday-Sunday: 1-7)
  -file string
     Path to crontab file
  -h Print help then exit
  -locale string
     Output description in which locale (default "en")
  -print-all
     Print all lines which is not a valid cron
  -v Print app version then exit
  -verbose
     Output description in verbose format

Examples:
  $ hcron "0 15 * * 1-5"
  $ hcron "0 */10 9 * * 1-5 2020"
  $ hcron -locale fr "0 */10 9 * * 1-5 2020"
  $ hcron -file /var/spool/cron/crontabs/mycronfile
  $ another-app | hcron
  $ another-app | hcron --dow-starts-at-one --24-hour -locale es

帮助文档还是很友好的。


文末「阅读原文」可直达项目首页。


今天的项目大家觉得怎么样吗?如果你喜欢,请在文章底部留言、点赞或关注转发,你的支持就是我持续更新的最大动力!



推荐阅读


福利

我为大家整理了一份从入门到进阶的Go学习资料礼包,包含学习建议:入门看什么,进阶看什么。关注公众号 「polarisxu」,回复 ebook 获取;还可以回复「进群」,和数万 Gopher 交流学习。

浏览 32
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报