timer in golang
To create a timer in Go, you can use the time
package. Here are the steps to create a timer in Go:
- Import the
time
package:
import "time"
- Create a channel of type
time.Time
to receive the time signal when the timer expires:
timer := make(chan time.Time)
- Start the timer by using the
time.AfterFunc
function. This function takes two arguments: the duration of the timer and a function to be executed when the timer expires:
time.AfterFunc(time.Second*5, func() {
timer <- time.Now()
})
In this example, the timer is set to expire after 5 seconds.
- Block the execution of your code until the timer expires by using the
<-timer
syntax:
<-timer
Once the timer expires, the current time will be sent to the timer
channel, and the <-timer
statement will unblock, allowing the code to continue executing.
That's it! With these steps, you can create a timer in Go and execute code when the timer expires. Remember to handle any errors that may arise during the process.