Created
October 17, 2021 08:37
-
-
Save yusufpapurcu/eed8c15284f28faace00636208666c8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
ctx, cancel := context.WithCancel(context.Background()) | |
go func() { | |
fmt.Println("Let's wait 5 minute") | |
WaitUntilWithContext(ctx, time.Minute*5) | |
fmt.Println("Hey!! Why we exited after 5 second !?!??!") | |
}() | |
time.Sleep(5 * time.Second) | |
cancel() | |
time.Sleep(10 * time.Second) | |
} | |
func WaitUntilWithContext(ctx context.Context, diff time.Duration) { | |
timer := time.NewTimer(diff) | |
defer timer.Stop() | |
select { | |
case <-timer.C: | |
return | |
case <-ctx.Done(): | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment