go语言定时器

来源:互联网 发布:中信证券mac版 编辑:程序博客网 时间:2024/05/29 14:44
[plain] view plaincopy
  1. package main  
  2.   
  3. import "fmt"  
  4. import "time"  
  5.   
  6. func main() {  
  7.         t := time.NewTimer(2 * time.Second)  
  8.         //v := <- t.C   
  9.         //fmt.Println(v)  
  10.         go onTime(t.C)  
  11.         fmt.Println("main thread")  
  12.         time.Sleep(10 * time.Second)  
  13.   
  14. }  
  15.   
  16. func onTime(c <-chan time.Time) {  
  17.         for now := range c {   
  18.                 // now := <- c  
  19.                 fmt.Println("onTime", now)  
  20.         }     
  21. }  



[plain] view plaincopy
  1. package main  
  2.   
  3. import "fmt"  
  4. import "time"  
  5.   
  6. func main() {  
  7.     time.AfterFunc(5 * time.Second, f1)  
  8.     time.AfterFunc(2 * time.Second, f2)  
  9.     fmt.Println("main thread")  
  10.     time.Sleep(10 * time.Second)  
  11. }  
  12.   
  13.   
  14. func f1() {  
  15.     fmt.Println("f1 done !")  
  16. }  
  17.   
  18. func f2() {  
  19.     fmt.Println("f2 done !")  
  20. }  


[plain] view plaincopy
  1. package main  
  2.   
  3. import "fmt"  
  4. import "time"  
  5.   
  6. var count int = 0  
  7.   
  8. func main() {  
  9.     t := time.Tick(2 * time.Second)  
  10.   
  11.     i := 0  
  12.     for now := range t {  
  13.         fmt.Println(now, doSomething())  
  14.         i++  
  15.         if i > 10 {  
  16.             break  
  17.         }  
  18.     }  
  19. }  
  20.   
  21. func doSomething() int {  
  22.     count++  
  23.     return count  
  24. }  
0 0