码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-04-11 09:54:26      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:http   href   defer   入门   struct   package   top   实现   port   

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

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

标签:http   href   defer   入门   struct   package   top   实现   port   

原文地址:https://blog.51cto.com/14744108/2486367

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!