Here, we will are going to learn about WithTimeout function in context package in Go with example in details.
The ‘WithTimeout‘ function is a part of the context package that returns a derived context and a cancellation function. The derived context is a copy of the parent context with a deadline set relative to the specified timeout duration. When the deadline is reached, the derived context is automatically canceled. This can be useful when you need to enforce a timeout on a long-running process or when you need to propagate a timeout through a chain of function calls.
Syntax:
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
Example:
Let’s create a simple example to demonstrate the use of the ‘WithTimeout’ function. We will create a small Go application that simulates a long-running process and shows how to use the ‘WithTimeout’ function to enforce a timeout on the process.
package main
import (
"context"
"fmt"
"time"
)
func longRunningProcess(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("Process stopped")
return
default:
fmt.Println("Process running...")
time.Sleep(1 * time.Second)
}
}
}
func main() {
parentCtx := context.Background()
ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second)
defer cancel()
go longRunningProcess(ctx)
time.Sleep(7 * time.Second)
fmt.Println("Main function completed")
}
In this example, the longRunningProcess
function simulates a long-running process by repeatedly printing “Process running…” every second. It uses the context’s Done
channel to listen for a cancellation signal. If a cancellation signal is received, it prints “Process stopped” and returns, effectively stopping the process.
In the main
function, we create a parent context using context.Background()
and then create a derived context and a cancellation function using the ‘WithTimeout’ function. We set a timeout of 5 seconds. We start the long-running process in a separate goroutine, passing the derived context to it. The main
function waits for 7 seconds before completing, giving the long-running process time to detect the timeout and terminate.
Output:
Process running... Process running... Process running... Process running... Process stopped Main function completed
To learn more about golang, Please refer given below link.
https://techieindoor.com/context-package-in-go/
References: