3
package main

import (
    "log"
    "time"
)

func main() {
    per := 10
    period := time.Duration(per) * time.Second
    log.Printf("period : %d sec\n\n", per)

    ticker := time.NewTicker(time.Until(time.Now().Truncate(period).Add(period)))
    for {
        curTime := <-ticker.C
        log.Printf("started %s", curTime.Format("2 15:04:05"))
        time.Sleep(5 * time.Second)
        log.Printf("ended %s\n\n", curTime.Format("2 15:04:05"))
    }

}

When I use time.Sleep inside ticker, ticker stop working properly, I want that ticker start every 10 sec, but I see results as on screenshot. How can I do it properly? enter image description here

StrRoma
  • 31
  • 1

2 Answers2

2

Your code is working, but you're printing the wrong time.

    for {
        curTime := <-ticker.C
        log.Printf("started %s", curTime.Format("2 15:04:05"))
        time.Sleep(5 * time.Second)
        log.Printf("ended %s\n\n", curTime.Format("2 15:04:05"))
    }

curTime is the time of the tick, so this prints the same time twice. Instead you should use time.Now() to get the current time.

    for {
        tickTime := <-ticker.C
        log.Printf("tick %s", tickTime.Format("2 15:04:05"))
        time.Sleep(5 * time.Second)
        log.Printf("after sleep %s\n\n", time.Now().Format("2 15:04:05"))
    }

And, as NewTicker takes a Duration, it can be simplified.

    per := 10
    period := time.Duration(per) * time.Second

    // Rather than printing the number in `per` and assuming it's
    // seconds, print the duration which can format itself.
    log.Printf("period : %s\n\n", period)

    // NewTicker takes a Duration which we already have.
    ticker := time.NewTicker(period)

Then you get the correct 5 second sleep within 10 second ticks.

2021/03/25 16:02:49 period : 10 sec

2021/03/25 16:02:59 tick 25 16:02:59
2021/03/25 16:03:04 after sleep 25 16:03:04

2021/03/25 16:03:09 tick 25 16:03:09
2021/03/25 16:03:14 after sleep 25 16:03:14
Schwern
  • 153,029
  • 25
  • 195
  • 336
0

Replace

ticker := time.NewTicker(time.Until(time.Now().Truncate(period).Add(period)))

with

ticker := time.NewTicker(period)

See if that works.

maxm
  • 3,412
  • 1
  • 19
  • 27