Created
August 11, 2020 01:51
-
-
Save andreleoni/9c6819eb7b4f7c914ac4faa080551a09 to your computer and use it in GitHub Desktop.
context studies
This file contains hidden or 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 ( | |
"context" | |
"fmt" | |
"time" | |
) | |
func main() { | |
ctx, cancel := context.WithTimeout( | |
context.Background(), | |
time.Duration(3*time.Second)) | |
defer cancel() | |
go func(ctx context.Context) { | |
defer cancel() | |
simulate a process that takes 2 second to complete | |
time.Sleep(1 * time.Second) | |
}(ctx) | |
select { | |
case <-ctx.Done(): | |
switch ctx.Err() { | |
case context.DeadlineExceeded: | |
fmt.Println("context timeout exceeded") | |
case context.Canceled: | |
// spew.Dump(context) | |
fmt.Println("context cancelled by force. whole process is complete") | |
} | |
case <-time.After(2 * time.Second): // Successfully | |
fmt.Println("without error") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment