Tickers – running something periodically
It may be a reasonable idea to run a function periodically using repeated calls to AfterFunc
:
var periodicTask func() periodicTask = func() { DoSomething() time.AfterFunc(time.Second, periodicTask) } time.AfterFunc(time.Second,periodicTask)
With this approach, each run of the function will schedule the next one, but variations in the running duration of the function will accumulate over time. This may be perfectly acceptable for your use case, but there is a better and easier way to do this: use time.Ticker
.
time.Ticker
has an API very similar to that of time.Timer
: You can create a ticker using time.NewTicker
, and then listen to a channel that will periodically deliver a tick until it is explicitly stopped. The period of the tick will not change based on the running time of the listener. The following program prints the number of milliseconds elapsed since the beginning of the program for...