The use of the Go Language sample-timer timer

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.