How do I set deadlines and timeouts with context?

In Go, you can manage deadlines and timeouts using the `context` package, which allows you to pass a context through your application to control cancellation signals and deadlines.

Context is useful for managing timeouts in functions, making it easy to handle long-running tasks. Here’s an example of how to set a deadline and timeout using context:

package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() go func() { // Simulating a long-running task time.Sleep(3 * time.Second) fmt.Println("Task finished") cancel() // Cancel the context when the task finishes }() select { case <-ctx.Done(): // Handle the case when the context is done (either timeout or manually canceled) fmt.Println("Operation timed out:", ctx.Err()) } fmt.Println("Finished execution") }

Go context deadlines timeouts goroutines cancellation