Administrator
Administrator
Published on 2025-03-10 / 4 Visits
0
0

cron

golang的定期、定时任务

github: https://github.com/robfig/cron

依赖

go get github.com/robfig/cron

实例

	c := cron.New() //用本地时间时区

	c := cron.NewWithLocation(time.FixedZone("UTC+3", 10800)) //特定时区,UTC+3俄罗斯时间,10800是和世界标准时间的时间差异。如果是西时区则填写负数

AddFunc

	/*
		秒 分 时 日 月 周(0表示周天,1表示周1)

		50 1 23 * * *:每天23点1分50秒执行一次
		* 1 23 * * *:每天23点1分秒执行N次,函数会每秒执行一次直到23:02分停止
		50 1 23 * * 1:每个周一,23点1分50秒执行一次
		50 1 23 * 3 *:三月的每天,23点1分50秒执行一次
		50 1 23 10 * *:每个月的10号,23点1分50秒执行一次
		50 1 23 10 3 *:每年3月10号,23点1分50秒执行一次
	*/
	//   */5 * * * * * 每五秒执行一次(用于测试)
	//   * */5 * * * * 每五分钟执行一次(用于测试)
	c.AddFunc("* 30 * * * *", func() {
		fmt.Println("30分,工作咯1")
		time.Sleep(time.Second * 5)

	})
	c.AddFunc("* 40 * * * *", func() {
		fmt.Println("40分,工作咯")
		time.Sleep(time.Second * 2)
	})
	c.Start() //运行非阻塞的任务调度,在恰当的时间执行AddFunc和AddJob添加的任务
	// c.Stop() 停止任务调度,已在运行的不影响
	time.Sleep(time.Hour) //让程序不退出

AddJob

定义一个结构体并实现Run方法

//需写在最外层
type CustomJob struct {
	CustomField string
}

func (ins *CustomJob) Run() {
	fmt.Println("val", ins.CustomField)
}
	c.AddJob("45 31 * * * *", &CustomJob{
		CustomField: "test value",
	})


Comment