Created
January 19, 2018 09:08
-
-
Save deividaspetraitis/cd0f4a8d5291c967de89a91ca32da6d8 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
package main | |
import ( | |
"fmt" | |
"time" | |
"runtime" | |
"context" | |
) | |
func main() { | |
// ctx | |
ctx, cancel := context.WithTimeout(context.Background(), time.Hour) | |
// This function returns error | |
go Perform(ctx) | |
// ... | |
time.Sleep(time.Second * 5) | |
cancel() | |
fmt.Println("Ctx canceled") | |
// runtime.Goexit makes to crash program in case | |
// there is no running routines | |
time.Sleep(time.Hour) | |
// too bad :( | |
runtime.Goexit() | |
} | |
// Following function is often found in many examples | |
// It returns ctx.Err() but for what reason since there is no | |
// way to catch it in such manner | |
func Perform(ctx context.Context) error { | |
for { | |
SomeFunction(ctx) | |
select { | |
case <-ctx.Done(): | |
fmt.Println("ctx is canceled, return error") | |
return ctx.Err() | |
case <-time.After(time.Second): // sleep 1 sec | |
fmt.Println("ctx is not canceled, continue immediately") | |
} | |
} | |
return nil | |
} | |
func SomeFunction(ctx context.Context) { | |
fmt.Println("ping") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment