Golang 入门系列(八)如何实现定时任务,极简版!

前面讲介绍了Go 语言的基础入门及Golang的语法结构。同时也介绍Golang的接口及协程等内容。感兴趣的朋友可以先看看之前的文章。接下来说一说Golang 如何实现定时任务。

golang 实现定时服务很简单,只需要简单几步代码便可以完成,不需要配置繁琐的服务器,直接在代码中实现。

1、使用的包

<code>github.com/robfig/cron/<code>

2、示例

1、创建最简单的最简单cron任务

<code>

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

{} }/<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

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() 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中如何创建定时任务做了简单介绍,实际使用中,大家可以可结合配置需要定时执行的任务。



分享到:


相關文章: