You could just call sleep if you want
dur := 1 * time.Second
nextDur := 3 * time.Second
for {
time.Sleep(dur)
dur, nextDur = nextDur, dur
...
}
Or alternate the durations in a time.Timer
if you need to select
. This is what I would personally stick with, since you don't need to worry about the offset between two timers skewing due to scheduling inconsistencies.
dur := 1 * time.Second
nextDur := 3 * time.Second
timer := time.NewTimer(dur)
for {
select {
case t := <-timer.C:
dur, nextDur = nextDur, dur
timer.Reset(dur)
...
}
...
}
Or run 2 timers offset by the smaller interval
dur1 := 1 * time.Second
dur2 := 3 * time.Second
timer1 := time.NewTimer(dur1)
timer2 := time.NewTimer(dur1 + dur2)
for {
select {
case t := <-timer1.C:
timer1.Reset(dur1 + dur2)
fmt.Println("timer1:", t)
case t := <-timer2.C:
timer2.Reset(dur1 + dur2)
fmt.Println("timer2:", t)
}
}
And you could also run interleaved Tickers like you originally tried, but that requires a little more coordination to delay the start of one of them
dur1 := 1 * time.Second
dur2 := 3 * time.Second
ticker1 := time.NewTicker(dur1)
ticker2 := time.NewTicker(dur1 + dur2)
var once sync.Once
delayOnce := func() {
ticker1.Stop()
ticker1 = time.NewTicker(dur1 + dur2)
}
for {
select {
case t := <-ticker1.C:
once.Do(delayOnce)
fmt.Println("ticker1:", t)
case t := <-ticker2.C:
fmt.Println("ticker2:", t)
}
}