This is a creation in
Article, where the information may have evolved or changed.
The programming goal is to perform a task after the program starts for 10 seconds, such as a log dump (rotate), which is performed every 15 seconds later.
First-time design
package mainimport ( "time" "fmt")func main() { timer := time.NewTimer(10 * time.Second) fmt.Println(time.Now()) for { select { case <-timer.C: fmt.Println(time.Now()) time.Sleep(1 * time.Second) timer.Reset(15 * time.Second) } }}
Obviously, before setting the next timer ( timer.Reset(15 * time.Second) ), it consumes a little bit of time, and even the millisecond delay is bound to generate a cumulative error.
To make the problem more noticeable, add a second Sleep to the program. The test results are as follows:
2017-07-18 23:16:24.791623 +0800 CST2017-07-18 23:16:34.7917567 +0800 CST2017-07-18 23:16:50.7920782 +0800 CST2017-07-18 23:17:06.7929373 +0800 CST2017-07-18 23:17:22.7944063 +0800 CST2017-07-18 23:17:38.7951302 +0800 CST2017-07-18 23:17:54.7968096 +0800 CST2017-07-18 23:18:10.7985468 +0800 CST2017-07-18 23:18:26.7993588 +0800 CST2017-07-18 23:18:42.7996568 +0800 CST2017-07-18 23:18:58.8008621 +0800 CST
The improved program
package mainimport ( "time" "fmt")func main() { next := time.Now().Add(10 * time.Second) timer := time.NewTimer(next.Sub(time.Now())) fmt.Println(time.Now()) for { select { case <-timer.C: fmt.Println(time.Now()) time.Sleep(1 * time.Second) next = next.Add(15 * time.Second) timer.Reset(next.Sub(time.Now())) } }}
Simply put, add a time variable next, and calculate the execution time of the next task before setting the timer.
And the timer is used next - Now() to set. The test results are as follows:
2017-07-18 23:16:20.2456695 +0800 CST2017-07-18 23:16:30.2466397 +0800 CST2017-07-18 23:16:45.2457191 +0800 CST2017-07-18 23:17:00.2458328 +0800 CST2017-07-18 23:17:15.2451861 +0800 CST2017-07-18 23:17:30.2452624 +0800 CST2017-07-18 23:17:45.2468138 +0800 CST2017-07-18 23:18:00.245947 +0800 CST
From the above results, the accuracy can be controlled in ±2ms. Can fully meet the needs of the scheduled dump log file.