這個Go開源工具有點意思
作為程序員,特別是后端,應(yīng)該離不開定時任務(wù),所以 CRON 表達(dá)式少不了。但你可能有這樣的煩惱:
Linux 的 Cron 是 5 或 6 位的,而 Go 庫中的是 7 位的(支持到秒); 一個 CRON 表達(dá)式,看不懂是啥意思;比如 0 23 ? * MON-FRI你知道是什么意思嗎?
如果有一個工具或庫,能夠?qū)⑦@個表達(dá)式轉(zhuǎn)為人類可讀的方式,這樣非技術(shù)人員也可以看懂了。
今天還真發(fā)現(xiàn)一個,使用 Go 語言實現(xiàn)的。
項目地址:https://github.com/lnquy/cron,它可以作為單獨的工具使用,也可以作為庫集成到你的程序中。
不過這個不是原創(chuàng),是借鑒 C# 庫 https://github.com/bradymholt/cron-expression-descriptor 和 JavaScript 庫 https://github.com/bradymholt/cRonstrue。
這個庫強大的地方在于支持全球 26 種語言。比如文章開頭的表達(dá)式,轉(zhuǎn)換后如下:
$ 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(默認(rèn)是 $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
幫助文檔還是很友好的。
文末「閱讀原文」可直達(dá)項目首頁。
今天的項目大家覺得怎么樣嗎?如果你喜歡,請在文章底部留言、點贊或關(guān)注轉(zhuǎn)發(fā),你的支持就是我持續(xù)更新的最大動力!
推薦閱讀
評論
圖片
表情
