This example demonstrates the usage of a simple timer in Go. The program shows how to create a timer that fires after a specified duration and performs an action after the timer expires.
- This example covers the basic usage of Go's
time.Timer
to schedule an event after a delay. - The program waits for the timer to fire after 2 seconds, and once the timer fires, it prints a message to the console.
package main
import (
"fmt"
"time"
)
func main() {
// Basic Example: Simple Timer
// Create a basic timer that fires after 2 seconds
// Create a timer that will fire after 2 seconds
timer := time.NewTimer(2 * time.Second)
fmt.Println("Waiting for the timer to fire...")
// Block until the timer's channel sends a value
<-timer.C
fmt.Println("Timer fired!")
}
-
Make sure you have Go installed. If not, you can download it from here.
-
Clone this repository:
git clone https://github.com/Rapter1990/go_sample_examples.git
-
Navigate to the
001_simple_timer
directory:cd go_sample_examples/020_timers/001_simple_timer
-
Run the Go program:
go run 001_simple_timer.go
When you run the program, you should see the following output:
Waiting for the timer to fire...
Timer fired!