0
是否有可能每天中午執行代碼?該程序正在處理用戶輸入剩餘的運行時間,但需要在中午運行一個函數來輸出一些文本。什麼是最有效的方法來做到這一點?Golang中午的運行代碼
是否有可能每天中午執行代碼?該程序正在處理用戶輸入剩餘的運行時間,但需要在中午運行一個函數來輸出一些文本。什麼是最有效的方法來做到這一點?Golang中午的運行代碼
所以你需要間隔定時器運行中午日常生活的一個功能,你可以使用:
time.AfterFunc()
或time.Tick()
或time.Sleep()
或time.Ticker
首當節目開始計算時間間隔的啓動時間,直到明年第一中午使用一些等待(例如time.Sleep
或...),然後在下一個時間間隔使用24 * time.Hour
間隔。
time.Sleep
示例代碼:
package main
import "fmt"
import "time"
func noonTask() {
fmt.Println(time.Now())
fmt.Println("do some job.")
}
func initNoon() {
t := time.Now()
n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
d := n.Sub(t)
if d < 0 {
n = n.Add(24 * time.Hour)
d = n.Sub(t)
}
for {
time.Sleep(d)
d = 24 * time.Hour
noonTask()
}
}
func main() {
initNoon()
}
,你可能會改變主本(或者你需要的任何東西):使用time.AfterFunc
func main() {
go initNoon()
// do normal task here:
for {
fmt.Println("do normal task here")
time.Sleep(1 * time.Minute)
}
}
:
package main
import (
"fmt"
"sync"
"time"
)
func noonTask() {
fmt.Println(time.Now())
fmt.Println("do some job.")
time.AfterFunc(duration(), noonTask)
}
func main() {
time.AfterFunc(duration(), noonTask)
wg.Add(1)
// do normal task here
wg.Wait()
}
func duration() time.Duration {
t := time.Now()
n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
if t.After(n) {
n = n.Add(24 * time.Hour)
}
d := n.Sub(t)
return d
}
var wg sync.WaitGroup
使用time.Ticker
:
package main
import (
"fmt"
"sync"
"time"
)
var ticker *time.Ticker = nil
func noonTask() {
if ticker == nil {
ticker = time.NewTicker(24 * time.Hour)
}
for {
fmt.Println(time.Now())
fmt.Println("do some job.")
<-ticker.C
}
}
func main() {
time.AfterFunc(duration(), noonTask)
wg.Add(1)
// do normal task here
wg.Wait()
}
func duration() time.Duration {
t := time.Now()
n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
if t.After(n) {
n = n.Add(24 * time.Hour)
}
d := n.Sub(t)
return d
}
var wg sync.WaitGroup
看:
https://github.com/jasonlvhit/gocron
Golang - How to execute function at specific times
Golang: Implementing a cron/executing tasks at a specific time