Golang當中的定時器

LiuYanYGZ發表於2024-09-04

參考:https://blog.csdn.net/qq_56999918/article/details/130499688

  1 package main
  2 
  3 import (
  4     "fmt"
  5     "time"
  6 )
  7 
  8 func Timer_stop(t *time.Timer) {
  9     if nil != t {
 10         t.Stop()
 11     }
 12 }
 13 
 14 
 15 func Timer_interval(delay_ms int, interval_ms int, fn func() ) *time.Timer {
 16     fmt.Printf("Timer_interval delay_ms=%d, interval_ms=%d\n", delay_ms, interval_ms)
 17     t:= time.NewTimer(time.Duration(delay_ms) * time.Millisecond)
 18     go timer_interval_do(t, fn, interval_ms)
 19     
 20     return t
 21 }
 22 
 23 func timer_interval_do(t *time.Timer, fn func(), interval_ms int) {
 24     for {
 25         select {
 26             case <- t.C:
 27             fmt.Println("timer_do timer triggered")
 28             t.Reset(time.Millisecond * time.Duration(interval_ms))
 29             fn()
 30         }
 31     }
 32 }
 33 
 34 func Timer_once(delay_ms int, fn func() ) *time.Timer {
 35     fmt.Printf("Timer_interval delay_ms=%d\n", delay_ms)
 36     t:= time.NewTimer(time.Duration(delay_ms) * time.Millisecond)
 37     go timer_once_do(t, fn)
 38     
 39     return t
 40 }
 41 
 42 func timer_once_do(t *time.Timer, fn func()) {
 43     for {
 44         select {
 45             case <- t.C:
 46             fmt.Println("timer_do timer triggered")
 47             t.Stop()
 48             fn()
 49         }
 50     }
 51 }
 52 ///////////////////////////////////////////////////////  以下是測試用例
 53 var mydo_is_doing = 0
 54 
 55 func mydo_thread() {
 56 
 57     mydo_is_doing = 1
 58 
 59     for i:=0; i < 20; i += 1 {
 60         fmt.Printf("timer doing, %d\n", i)
 61         time.Sleep(1*time.Second)
 62     }
 63 
 64     mydo_is_doing = 0
 65 }
 66 
 67 func mydo() {
 68     fmt.Println("mydo timer triggered")
 69 
 70     if 0 != mydo_is_doing {
 71         fmt.Println("mydo timer is doing, ignore this")
 72         return
 73     }
 74 
 75     go mydo_thread()
 76 }
 77 
 78 func mydo_once() {
 79     fmt.Println("mydo_once timer triggered")
 80     for i:=0; i < 20; i += 1 {
 81         fmt.Printf("timer_oncccccccccccccccccccccce doing, %d\n", i)
 82         time.Sleep(1*time.Second)
 83     }
 84 }
 85 
 86 func main() {
 87     t:=Timer_interval(2000, 5000, mydo)
 88     t2:=Timer_once(3000, mydo_once)
 89     fmt.Println("####################1")
 90     time.Sleep(13*time.Second)
 91     fmt.Println("####################2")
 92     Timer_stop(t2)
 93     Timer_stop(t)
 94     fmt.Println("####################3")
 95     time.Sleep(50*time.Second)
 96     fmt.Println("####################4")
 97 
 98 
 99 }
100 
101 ///////////////////////////////////////////////////////  以上是測試用例

相關文章