github.com/robfig/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
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...
以上,就將Golang中如何建立定時任務作了簡單介紹,實際使用中,你們能夠可結合toml yaml 配置須要定時執行的任務。html