Skip to content

Instantly share code, notes, and snippets.

@dtest11
Created March 25, 2021 10:43
Show Gist options
  • Save dtest11/007e303bcf5486b5842bf26107d2be0d to your computer and use it in GitHub Desktop.
Save dtest11/007e303bcf5486b5842bf26107d2be0d to your computer and use it in GitHub Desktop.
cron.go
package main
import (
"fmt"
"log"
"os/exec"
"time"
"github.com/robfig/cron"
)
func SetSystemDate(newTime time.Time) error {
_, lookErr := exec.LookPath("date")
if lookErr != nil {
fmt.Printf("Date binary not found, cannot set system date: %s\n", lookErr.Error())
return lookErr
} else {
//dateString := newTime.Format("2006-01-2 15:4:5")
dateString := newTime.Format("2 Jan 2006 15:04:05")
fmt.Printf("Setting system date to: %s\n", dateString)
args := []string{"--set", dateString}
return exec.Command("date", args...).Run()
}
}
func main() {
i := 0
c := cron.New()
spec := "*/5 * * * *"
spec = "3,15 8-11 */2 * *" // 每周一上午8点到11点的第3和第15分钟执行
spec = "0 20 17 ? * MON-FRI" // 周一到周五的每天 17:20 执行
spec = "0 38 17 ? * 1,2,3,4,5,6,7" // 周一到周五的每天 17:20 执行
for {
now := time.Now()
stop := make(chan struct{})
if err := SetSystemDate(now.AddDate(0, 0, 1)); err != nil {
panic(err)
}
spec = fmt.Sprintf("0 %d 17 ? * 1,2,3,4,5,6,7", now.Minute()+1)
log.Println("------", spec)
err := c.AddFunc(spec, func() {
i++
log.Println("execute per 5 seconds", i)
close(stop)
})
if err != nil {
panic(err)
}
c.Start()
<-stop
}
}
// Seconds Minutes Hours DayofMonth Month DayofWeek Year或
// Seconds Minutes Hours DayofMonth Month DayofWeek
// 0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
// "0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发
// 0 0 2 1 * ? * 表示在每月的1日的凌晨2点调度任务
// 0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业
// 0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作
/**
docker run -it -v `pwd`:/go/src/abc ubuntu:20.04 bash
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment