ticker

ticker

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
package main import ( "fmt" "time" ) func main() { ticker := time.NewTicker(time.Second) defer ticker.Stop() done := make(chan bool) go func() { time.Sleep(10 * time.Second) done <- true }() for { select { case <-done: fmt.Println("Done!") return case t := <-ticker.C: fmt.Println("Current time: ", t) } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
package main import ( "fmt" "math/rand" "time" ) func main() { ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() done := make(chan bool) changeTickerDuration := make(chan bool) go func() { t := time.After(5 * time.Second) for { select { case <-t: done <- true return case v, ok := <-changeTickerDuration: fmt.Printf("%t,%t\n", v, ok) if v && ok { t = time.After(10 * time.Second) ticker.Reset(1 * time.Second) fmt.Println("had changed ticker duration") } } } }() go func() { time.Sleep(2 * time.Second) r := rand.Intn(100) if r > 50 { changeTickerDuration <- true fmt.Println("heavy task, need to change ticker") } else { changeTickerDuration <- false } }() for { select { case <-done: fmt.Println("Done!") return case curTime := <-ticker.C: fmt.Println("Current time: ", curTime) } } }
最后修改 October 10, 2024: 更新 (a4b8f85)