Menu Close

WithDeadline function in context package in Go

Here, we will are going to learn about WithDeadline function in context package in Go with example in details.

The ‘WithDeadline’ 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 an additional deadline property. 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 deadline through a chain of function calls.

Syntax:

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)

Example:

Let’s create a simple example to demonstrate the use of the ‘WithDeadline’ function. We will create a small Go application that simulates a long-running process and shows how to use the ‘WithDeadline’ function to enforce a deadline 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()

	deadline := time.Now().Add(5 * time.Second)

	ctx, cancel := context.WithDeadline(parentCtx, deadline)

	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 ‘WithDeadline’ function. We set a deadline of 5 seconds from the current time. 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 deadline 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:

https://golang.org/doc/

Posted in context, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *