Timers in Go
Go: Timers
Timers can be created using the time package. it allow you to schedule a function to be called after a certain amount of time has passed.
Here's an example:
package main
import (
"fmt"
"time"
)
func main() {
// create a timer that will expire after 2 seconds
timer := time.NewTimer(2 * time.Second)
fmt.Println("Waiting for timer to expire...")
// block until the timer expires
<-timer.C
fmt.Println("Timer expired!")
}
In this example, we create a new timer that will expire after 2 seconds using the NewTimer
function. We then wait for the timer to expire by blocking on the timer's C
channel.
When the timer expires, the C
channel is closed and the blocking operation on <-timer.C
is unblocked. We then print out a message indicating that the timer has expired.
If you want to stop a timer before it expires, you can call the Stop method on the timer. Here's an example:
package main
import (
"fmt"
"time"
)
func main() {
// create a timer that will expire after 5 seconds
timer := time.NewTimer(5 * time.Second)
fmt.Println("Waiting for timer to expire...")
// stop the timer before it expires
stopped := timer.Stop()
if stopped {
fmt.Println("Timer stopped before it could expire!")
} else {
fmt.Println("Timer expired before it could be stopped!")
}
}
In this example, we create a new timer that will expire after 5 seconds using the NewTimer
function. We then immediately stop the timer using the Stop
method. We check the return value of Stop to determine if the timer was stopped before it could expire or if it had already expired.
I hope this helps you understand how to use timers in Go! Let me know if you have any other questions.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go