-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"time" | ||
) | ||
|
||
func main() { | ||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) | ||
defer cancel() | ||
|
||
go performTask(ctx) | ||
|
||
select { | ||
case <-ctx.Done(): | ||
fmt.Printf("%T\n", ctx) | ||
fmt.Println(ctx) | ||
fmt.Printf("%T\n", ctx.Done()) | ||
fmt.Println(ctx.Done()) | ||
fmt.Println("Task timeout") | ||
} | ||
} | ||
|
||
// If performTask is not finished within 2 seconds, the program terminates | ||
func performTask(ctx context.Context) { | ||
select { | ||
case <-time.After(5 * time.Second): | ||
fmt.Println("Task completed") | ||
} | ||
|
||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"time" | ||
) | ||
|
||
func main() { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
|
||
go task(ctx) | ||
|
||
time.Sleep(2 * time.Second) | ||
cancel() | ||
time.Sleep(1 * time.Second) | ||
} | ||
|
||
func task(ctx context.Context) { | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
fmt.Println("Task terminated") | ||
return | ||
default: | ||
fmt.Println("Doing task") | ||
time.Sleep(300 * time.Millisecond) | ||
} | ||
} | ||
|
||
} |