前面講介紹了Go 語言的基礎入門及Golang的語法結構。同時也介紹Golang的接口及協程等內容。感興趣的朋友可以先看看之前的文章。接下來說一說Golang 如何實現定時任務。
golang 實現定時服務很簡單,只需要簡單幾步代碼便可以完成,不需要配置繁瑣的服務器,直接在代碼中實現。
1、使用的包
<code>github.com/robfig/cron/<code>
2、示例
1、創建最簡單的最簡單cron任務
<code>package
mainimport
("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
{} }/<code>
啟動後輸出如下:
<code>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...
/<code>
2、多個定時cron任務
<code>package
mainimport
("github.com/robfig/cron"
"fmt"
)type
TestJobstruct
{ }func
(this TestJob)
Run
()
{ fmt.Println("testJob1..."
) }type
Test2Jobstruct
{ }func
(this Test2Job)
Run
()
{ fmt.Println("testJob2..."
) }func
main
()
{ i :=0
c := cron.New() spec :="*/5 * * * * ?"
c.AddFunc(spec,func
()
{ i++ fmt.Println("cron running:"
, i) }) c.AddJob(spec, TestJob{}) c.AddJob(spec, Test2Job{}) c.Start()defer
c.Stop()select
{} }/<code>
啟動後輸出如下:
<code>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...
/<code>
3、cron 表達式
Go 實現的cron 表達式的基本語法跟linux 中的 crontab基本是類似的。cron(計劃任務),就是按照約定的時間,定時的執行特定的任務(job)。cron 表達式 表達了這種約定。 cron 表達式代表了一個時間集合,使用 6 個空格分隔的字段表示。如果對cron 表達式不清楚的,可以看看我之前介紹quartz.net 的文章:《 》。
4、最後
以上,就將Golang中如何創建定時任務做了簡單介紹,實際使用中,大家可以可結合配置需要定時執行的任務。