package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.Background()
c, fn := context.WithCancel(ctx)
go doSth(c)
time.Sleep(1 * time.Second)
fn()
time.Sleep(10 * time.Second)
}
func doSth(ctx context.Context) {
fmt.Println("doing")
time.Sleep(2 * time.Second)
fmt.Println("still doing")
select {
case <-ctx.Done():
fmt.Println("cancel")
return
}
}
OUTPUT:
doing
still doing
cancel
I don't know how to make this doSth function return when the context it get is canncel.
In another word, I want the output of this function is:
OUTPUT:
doing
cancel
CodePudding user response:
You can use a timer, which will send a message over a channel after the given duration. This allows you to add it in the select.
func main() {
ctx := context.Background()
c, fn := context.WithCancel(ctx)
go doSth(c)
time.Sleep(1 * time.Second)
fn()
time.Sleep(10 * time.Second)
}
func doSth(ctx context.Context) {
fmt.Println("doing")
timer := time.NewTimer(2 * time.Second)
select {
case <-timer.C:
fmt.Println("still doing")
case <-ctx.Done():
fmt.Println("cancel")
}
}