Instead of cronjob, you can schedule a job run at a specific time, run after X duration, panic retry,...
go get github.com/func25/gowait
Schedule a job run in 3 seconds later:
varstartint64funcmain() {
start=time.Now().Unix()
gowait.DurationJob(time.Second*3, showTime)
time.Sleep(time.Second*4)
}
funcshowTime() {
fmt.Println("show time:", time.Now().Unix() -start)
}The result of course will be:
show time: 3
Schedule a job run in 3 seconds later and also run EVERY 3 seconds, if you want to stop, just return nil in the job
varstartint64funcmain() {
start=time.Now().Unix()
gowait.DurationJobLoop(showTimeLoop, time.Second*3)
time.Sleep(time.Second*10)
}
funcshowTimeLoop() *time.Duration {
fmt.Println("show time:", time.Now().Unix()-start)
next:=time.Second*3return&next
}show time: 3show time: 6show time: 9To use our option, you should create an "option generator", in the below example, the job will run at 1 second later
- ZeroDuration: if the job return <= 0 duration time, then we apply 1 second to the duration (avoid spamming).
- MinDuration: this will be more prioritized than zeroDuration.
- PanicRetry: retry the job if any panic occurs and what time is it run next time.
varstartTimeint64funcmain() {
startTime=time.Now().Unix()
g:= gowait.RepeatOptGen{} "option generator"gowait.ScheduleJobLoop(loopTime, time.Now().Add(time.Second),
g.ZeroDuration(time.Second), // zeroDuration will be 2s (minDuration have higher priority)g.MinDuration(2*time.Second),
g.PanicRetry(true, 3*time.Second),
)
time.Sleep(time.Hour)
}
funcloopTime() *time.Time {
dis:=time.Now().Unix() -startTimefmt.Println("show time:", dis)
x:=time.Now().Add(time.Second*1) // run next 1 secondifdis==5 {
fmt.Println("zeroDuration")
x=time.Now() // test zeroDuration + minDuration
}
ifdis>10 { // test panicfmt.Println("panic")
panic("dis > 10")
}
return&x
}show time: 1show time: 3show time: 5zeroDurationshow time: 7show time: 9show time: 11panicshow time: 14panicshow time: 17panicshow time: 20panicThis lib is under developing, please notice when using it