Golang使用crontab

发布时间 2023-11-09 14:27:50作者: 朝阳1

要是记不住crontab格式,就去网上生成,在线crontab有很多。例如 https://www.pppet.net/

package main

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

/**
第一个*: second,范围(0 - 60)
第二个*: min,范围(0 - 59)
第三个*: hour,范围(0 - 23)
第四个*: day of month,范围(1 - 31)
第五个*: month,范围(1 - 12)
第六个*: day of week,范围(0 - 6) (0 to 6 are Sunday to Saturday)
*/
//每隔5秒执行一次:*/5 * * * * ?
//每隔1分钟执行一次:0 */1 * * * ?
//每天23点执行一次:0 0 23 * * ?
//每天凌晨1点执行一次:0 0 1 * * ?
//每月1号凌晨1点执行一次:0 0 1 1 * ?
//每周一和周三晚上22:30: 00 30 22 * * 1,3
//在线crontab https://www.pppet.net/

func main() {
	// 新建一个定时任务对象,根据cron表达式进行时间调度,cron可以精确到秒,大部分表达式格式也是从秒开始
	// 精确到秒
	cronTab := cron.New(cron.WithSeconds())
	// 定义定时器调用的任务函数
	task := func() {
		fmt.Println("hello world", time.Now())
	}
	// 定时任务,cron表达式,每五秒一次
	spec := "*/5 * * * * ?"
	// 添加定时任务
	cronTab.AddFunc(spec, task)
	// 启动定时器
	cronTab.Start()
	// 阻塞主线程停止
	select {}
}

func main2() {
	//直接配置时区
	nyc, _ := time.LoadLocation("Asia/Shanghai")
	// cron.New(cron.WithLocation(time.UTC))
	c := cron.New(cron.WithLocation(nyc), cron.WithSeconds())
	c.AddFunc("*/5 * * * * ?", func() {
		fmt.Println("5/s New York")
	})
	// 参数里面配置时区
	c.AddFunc("CRON_TZ=Asia/Tokyo */5 * * * * ?", func() {
		fmt.Println("5/s tokyo")
	})
	c.Start()
	select {}
}