Use context.WithDeadline to create a derived context that cancels automatically when a specific time.Time is reached. Always call the returned cancel function to release resources if the operation finishes early.
ctx, cancel := context.WithDeadline(parentCtx, time.Now().Add(5*time.Second))
defer cancel()
// Use ctx in your operation
The cancel function stops the timer and releases resources associated with the context. If you do not call it, the context and its timer will leak until the parent context is canceled or the deadline passes.