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...