SoFunction
Updated on 2025-03-01

Detailed explanation of the three implementation methods of Go timer

Sleep

Many times, some operations need to be performed periodically, and a timer is required. There are three ways to think about timers.

Source code location of this section/golang-mini…

Use Hibernation to let the currentGoroutineThe effect of timing is achieved by sleeping for a certain period of time. The disadvantage is that the program execution speed is uneven, resulting in uneven timing cycles.

for{
		(())
		(*1)
	}

Timer

GoThe language's built-in package specifies a time to start the time count. After the time is up, a notification will be sent to the outside world. The way to send notifications is to use<-chan TimeReturn to content.

The first method is to use directly at the waiting point, the effect andSleepLikewise, it gets stuck inside and is usedTimer

	(())
	<-(1*)
	(())

You can also split it and wait anywhere

	timer := (1 * )
	<-
	(())

But the above is just to delay one-time execution. Let's transform it into a timer.

    done := make(chan struct{})
	timer := (1 * )
	go func() {
		for {
			select {
			case <-:
				(())
				(1 * )
			case <-done:
				return
			}
		}
	}()
	<-(5* + *100)
	done <- struct{}{}
  • Definition subGoroutineThe purpose is to prevent deadlocks from being formed so that the timer can eventually exit. In actual projects, a permanent running timer may be required. Generally, it will also be defined in this way to not affect the main logic of the project. If your project is a timed task, I suggest writing it the same way, so that many timers can be registered without affecting each other.
  • doneIt is to determine whether the execution is over and prevent the mainGoroutineExit early.
  • There are only two examplescase, if there is any other waycaseNeed to give eachcaseDo it onceReset, ensure the reset timer.

Ticker

Compared with the timer implemented using the delay execution function,TickerIt's a timer (internal encapsulationTimer), it is very simple to use.

ticker := (1 * )
	go func() {
		for {
			<-
			(())
		}
	}()
	<-(5 *  + *100)
	()

existselectThe official timeout control scheme described in the section is very practical and is also used. Also usedandThese two built-in functions will not be explained here, and it is recommended to review them.

summary

Timers are generally used to perform tasks periodically, such as timed synchronization of data, calculating reports, and sending notifications.

  • Use Hibernation to let the currentgoroutineThe effect of sleeping for a certain period of time is that the speed of internal logic execution will affect the time difference of the timer and the exact interval cannot be achieved.
  • TimerSimilar toSleepThe delay processing ofchannelto get notifications, and can also be converted into a timer. Because it is a delay processing, remember to reset the time to achieve the effect of timing execution.
  • TickerThe ready-made timer is also encapsulated insideTimer

The above is the detailed content of the three implementation methods of Go timer. For more information about the implementation methods of Go timer, please pay attention to my other related articles!