Golang 入门系列-八怎样实现定时任务,极简版.

栏目: IT技术 · 发布时间: 4年前

内容简介:感谢平台分享-前面讲介绍了Go 语言的基础入门及Golang的语法结构。同时也介绍Golang的接口及协程等内容。感兴趣的朋友可以先看看之前的文章。接下来说一说Golang 如何实现定时任务。golang 实现定时服务很简单,只需要简单几步代码便可以完成,不需要配置繁琐的服务器,直接在代码中实现。

感谢平台分享- http://bjbsair.com/2020-04-10/tech-info/53303.html

前面讲介绍了 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 表达式

4、最后

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

程序员面试算法宝典

程序员面试算法宝典

猿媛之家 / / 机械工业 / 2018-09-01 / 69.0

一起来看看 《程序员面试算法宝典》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具