如何在每天的特定时间运行作业?

我想每天晚上9点打印出来。如何在 Go 中执行此操作?do my job


以下是我到目前为止所得到的:


timer := time.NewTimer(3 * time.Second)

for {

    now := time.Now()

    next := now.Add(time.Hour * 24)

    todayNine := time.Date(next.Year(), next.Month(), next.Day(), 9, 0, 0, 0, next.Location()).AddDate(0, 0, -1)

    todayFifteen := time.Date(next.Year(), next.Month(), next.Day(), 15, 0, 0, 0, next.Location()).AddDate(0, 0, -1)

    todayEnd := time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location()).AddDate(0, 0,  -1)

    if now.Before(todayNine) {

        timer.Reset(todayNine.Sub(now))

    } else if now.Before(todayFifteen) {

        timer.Reset(todayFifteen.Sub(now))

    } else if now.Before(todayEnd) {

        timer.Reset(todayEnd.Sub(now))

    }

    <- timer.C

    fmt.Println("do my job")

}


慕田峪4524236
浏览 100回答 1
1回答

德玛西亚99

我会使用包。https://pkg.go.dev/github.com/robfig/croncron文档中的示例:c := cron.New()c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })c.AddFunc("@hourly",&nbsp; &nbsp; &nbsp; func() { fmt.Println("Every hour") })c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })c.Start()..// Funcs are invoked in their own goroutine, asynchronously....// Funcs may also be added to a running Cronc.AddFunc("@daily", func() { fmt.Println("Every day") })..// Inspect the cron job entries' next and previous run times.inspect(c.Entries())..c.Stop()&nbsp; // Stop the scheduler (does not stop any jobs already running).
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go