Timers are used to perform tasks on a regular basis, sharing a piece of code:
Package Main Import" Time"Import"FMT"Func Main () {//new timer, triggered after two seconds, the Go trigger timer is very special, is to send a value in the channel of the timertimer1:= time. Newtimer (time. Second *2)//This is waiting for a signal in the channel, which will block for two seconds when executing this code .<-timer1. Cfmt.println ("Timer 1 Expired") //new timer, triggered after one secondTimer2:=Time . Newtimer (time. Second)//a new thread is opened to handle the post-trigger eventgo func () {//and so on when the trigger signals<-Timer2. Cfmt.println ("Timer 2 Expired")}()//because the wait signal above is in the new thread, the code continues to execute, stopping the timerSTOP2:=Timer2. Stop ()ifSTOP2 {fmt. Println ("Timer 2 stopped")}}
Code interpretation is shown in the comments.
The resulting output is:
Timer 1 Expired
Timer 2 stopped
Because the processing thread of Timer 2 is stopped before the signal, it will print a timer 2 stopped instead of a timer 2 expired
The use of the Go Language sample-timer timer