下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

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

作者:课课家教育     来源: 今日头条点击数:15167发布时间: 2020-04-08 14:21:55

标签: IT业界互联网计算机

软考,您想通过吗?一次通过才是硬道理

Go语言是谷歌2009发布的第二款开源编程语言

Go语言专门针对多处理器系统应用程序的编程进行了优化,使用Go编译的程序可以媲美C或C++代码的速度,而且更加安全、支持并行进程。

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

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

 

1、使用的包

github.com/robfig/cron

 

2、示例

1、创建最简单的最简单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 multijob.go

 

cron running: 1

 

testJob1...

 

testJob2...

 

testJob1...

 

cron running: 2

 

testJob2...

 

testJob1...

 

testJob2...

 

cron running: 3

 

cron running: 4

 

testJob1...

 

testJob2...

2、多个定时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...

3、cron 表达式

Go 实现的cron 表达式的基本语法跟Linux 中的 crontab基本是类似的。cron(计划任务),就是按照约定的时间,定时的执行特定的任务(job)。cron 表达式 表达了这种约定。 cron 表达式代表了一个时间集合,使用 6 个空格分隔的字段表示。如果对cron 表达式不清楚的,可以看看我之前介绍quartz.net 的文章:《Quartz.NET总结(二)CronTrigger和Cron表达式》。

 

4、最后

以上,就将Golang中如何创建定时任务做了简单介绍,实际使用中,大家可以可结合配置需要定时执行的任务。

Go是谷歌2009发布的第二款编程语言。2009年7月份,谷歌曾发布了Simple语言,它是用来开发Android应用互联网:Golang 入门系列(八)如何实现定时任务,极简版_IT业界_互联网_计算机_课课家Go Logo的一种BASIC语言.