Documentation
¶
Overview ¶
Package timer provides a context-aware Sleep function.
It offers a way to pause execution for a specified duration, while respecting context cancellation.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/goaux/timer"
)
func main() {
// Create a context with a timeout of 2 seconds
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Try to sleep for 1 second
fmt.Println("Starting sleep for 1 second")
err := timer.SleepCause(ctx, 1*time.Second)
if err != nil {
fmt.Printf("Sleep interrupted: %v\n", err)
} else {
fmt.Println("Sleep completed successfully")
}
// Try to sleep for 3 seconds (longer than the context timeout)
fmt.Println("Starting sleep for 3 seconds")
err = timer.Sleep(ctx, 3*time.Second)
if err != nil {
fmt.Printf("Sleep interrupted: %v\n", err)
} else {
fmt.Println("Sleep completed successfully")
}
}
Output: Starting sleep for 1 second Sleep completed successfully Starting sleep for 3 seconds Sleep interrupted: context deadline exceeded
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Sleep ¶
Sleep pauses the current goroutine for the specified duration or until the context is canceled.
It returns nil if the sleep completes normally, or the context's error if the context is canceled before the duration elapses.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/goaux/timer"
)
func main() {
// Create a context with a timeout of 2 seconds
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Try to sleep for 1 second
fmt.Println("Starting sleep for 1 second")
err := timer.Sleep(ctx, 1*time.Second)
if err != nil {
fmt.Printf("Sleep interrupted: %v\n", err)
} else {
fmt.Println("Sleep completed successfully")
}
// Try to sleep for 3 seconds (longer than the context timeout)
fmt.Println("Starting sleep for 3 seconds")
err = timer.Sleep(ctx, 3*time.Second)
if err != nil {
fmt.Printf("Sleep interrupted: %v\n", err)
} else {
fmt.Println("Sleep completed successfully")
}
}
Output: Starting sleep for 1 second Sleep completed successfully Starting sleep for 3 seconds Sleep interrupted: context deadline exceeded
func SleepCause ¶ added in v1.1.0
SleepCause pauses the current goroutine for the specified duration or until the context is canceled. It returns nil if the sleep completes normally, or the cause of the context cancellation (as returned by context.Cause) if canceled.
This function requires Go 1.20+ to use context.Cause. It provides more detailed error information compared to Sleep.
Types ¶
This section is empty.