使用举例

package main

import (
	"fmt"
	"github.com/robfig/cron"
)

//主函数
func main() {
	cron2 := cron.New() //创建一个cron实例

	//执行定时任务(每5秒执行一次)
	err:= cron2.AddFunc("*/5 * * * * *", print5)
	if err!=nil{
	   fmt.Println(err)
	}

	//启动/关闭
	cron2.Start()
	defer cron2.Stop()
	select {
	  //查询语句,保持程序运行,在这里等同于for{}
	}
}

//执行函数
func print5()  {
     fmt.Println("每5s执行一次cron")
}

配置

┌─────────────second 范围 (0 - 60)
│ ┌───────────── min (0 - 59)
│ │ ┌────────────── hour (0 - 23)
│ │ │ ┌─────────────── day of month (1 - 31)
│ │ │ │ ┌──────────────── month (1 - 12)
│ │ │ │ │ ┌───────────────── day of week (0 - 6)
│ │ │ │ │ │
│ │ │ │ │ │
*  *  *  *  *  *  

多个crontab任务

package main

import (
	"fmt"

	"github.com/robfig/cron"
)

type TestJob struct {
}

func (this TestJob) Run() {
	fmt.Println("testJob1...")
}

type Test2Job struct {
}

func (this Test2Job) Run() {
	fmt.Println("testJob2...")
}

//启动多个任务
func main() {
	c := cron.New()
	spec := "*/5 * * * * ?"
	//AddJob方法
	c.AddJob(spec, TestJob{})
	c.AddJob(spec, Test2Job{})
	//启动计划任务
	c.Start()
	//关闭着计划任务, 但是不能关闭已经在执行中的任务.
	defer c.Stop()

	select {}
}

/*
testJob1...
testJob2...
testJob1...
testJob2...
*/