您的位置 首页 golang

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

前面讲介绍了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 的文章:《 》。

4、最后

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

推荐阅读:

文章来源:智云一二三科技

文章标题:Golang 入门系列(八)如何实现定时任务,极简版

文章地址:https://www.zhihuclub.com/91184.shtml

关于作者: 智云科技

热门文章

网站地图