Sobes.tech
Junior — Middle

What is the difference between using the WithTimeout function and WithDeadline in the context of execution time control?

sobes.tech AI

Answer from AI

The WithTimeout and WithDeadline functions in Go are used to create a context with a time limit, but they differ in how this limit is set:

  • WithTimeout(parent, timeout) creates a context that is automatically canceled after the specified duration timeout from the current moment. That is, the timer starts when called.

  • WithDeadline(parent, deadline) creates a context that is canceled at a specific point in time deadline (of type time.Time). This allows setting an exact time when the context will expire.

Example:

ctx1, cancel1 := context.WithTimeout(context.Background(), 5*time.Second)
// ctx1 will be canceled after 5 seconds from now

deadline := time.Now().Add(5 * time.Second)
ctx2, cancel2 := context.WithDeadline(context.Background(), deadline)
// ctx2 will be canceled exactly at the deadline time

Thus, WithTimeout is convenient when you need to specify a duration, while WithDeadline is useful when a specific point in time is important.