This repository demonstrates how to use the time.After
function in Go. It includes an example of creating a simple timer that waits for a specified duration and fires once, providing a straightforward alternative to time.NewTimer
.
- This example covers how to use the
time.After
function in Go to wait for a specific duration. - The
time.After
function returns a channel that will receive the current time after the specified duration has passed.
package main
import (
"fmt"
"time"
)
func main() {
// Using time.After
// time.After is a simpler alternative to time.NewTimer for creating a timer that only needs to fire once.
// It returns a channel that will receive the current time after the specified duration.
fmt.Println("Waiting for 2 seconds...")
// Wait for 2 seconds using time.After
<-time.After(2 * time.Second)
fmt.Println("2 seconds passed.")
}
-
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
004_using_time_after
directory:cd go_sample_examples/020_timers/004_using_time_after
-
Run the Go program:
go run 004_using_time_after.go
When you run the program, you should see the following output:
Waiting for 2 seconds...
2 seconds passed.