Sobes.tech
Junior — Middle

Milline on erinevus WithTimeout ja WithDeadline funktsioonide kasutamisel täitmisaja kontrolli kontekstis?

sobes.tech AI

Vastus AI-lt

In Go, the functions WithTimeout and WithDeadline 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 automatically cancels after the specified timeout duration from the current moment. That is, the timer starts at the moment of invocation.

  • WithDeadline(parent, deadline) creates a context that cancels at a specific 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

Therefore, WithTimeout is convenient when you want to specify a duration, and WithDeadline when an exact point in time is important.