1、cron 表達式的基本格式
Go 實現的cron 表達式的基本語法跟linux 中的 crontab基本是類似的。cron(計划任務),就是按照約定的時間,定時的執行特定的任務(job)。cron 表達式 表達了這種約定。 cron 表達式代表了一個時間集合,使用 6 個空格分隔的字段表示。如果對cron 表達式不清楚的,可以看看我之前介紹quartz.net 的文章,
Quartz.NET總結(二)CronTrigger和Cron表達式 。
2、使用的包
github.com/robfig/cron
3、示例
- 創建最簡單的最簡單cron任務
package main
import (
"github.com/robfig/cron"
"fmt"
)
func main() {
i := 0
c := cron.New()
spec := "*/5 * * * * ?"
c.AddFunc(spec, func() {
i++
fmt.Println("cron running:", i)
})
c.Start()
select{}
}
啟動后輸出如下:
D:\Go_Path\go\src\cronjob>go run singlejob.go cron running: 1 cron running: 2 cron running: 3 cron running: 4 cron running: 5
- 多個定時cron任務
package main import ( "github.com/robfig/cron" "fmt" ) type TestJob struct { } func (this TestJob)Run() { fmt.Println("testJob1...") } type Test2Job struct { } func (this Test2Job)Run() { fmt.Println("testJob2...") } //啟動多個任務 func main() { i := 0 c := cron.New() //AddFunc spec := "*/5 * * * * ?" c.AddFunc(spec, func() { i++ fmt.Println("cron running:", i) }) //AddJob方法 c.AddJob(spec, TestJob{}) c.AddJob(spec, Test2Job{}) //啟動計划任務 c.Start() //關閉着計划任務, 但是不能關閉已經在執行中的任務. defer c.Stop() select{} }
啟動后輸出如下:
D:\Go_Path\go\src\cronjob>go run multijob.go cron running: 1 testJob1... testJob2... testJob1... cron running: 2 testJob2... testJob1... testJob2... cron running: 3 cron running: 4 testJob1... testJob2...
4、最后
以上,就將Golang中如何創建定時任務做了簡單介紹,實際使用中,大家可以可結合toml yaml 配置需要定時執行的任務。