diff --git a/reuse/golang/src/package/time/Makefile b/reuse/golang/src/package/time/Makefile new file mode 100644 index 0000000..299e00d --- /dev/null +++ b/reuse/golang/src/package/time/Makefile @@ -0,0 +1,9 @@ + +example: + go run example.go + +ticker_example: + go run ticker_example.go + +timer_example: + go run timer_example.go diff --git a/reuse/golang/src/package/time/ticker_example.go b/reuse/golang/src/package/time/ticker_example.go new file mode 100644 index 0000000..aeef6db --- /dev/null +++ b/reuse/golang/src/package/time/ticker_example.go @@ -0,0 +1,33 @@ +package main + +// 是一个定时触发的计时器,它会以一个间隔(interval)往Channel发送一个事件(当前时间),而Channel的接收者可以以固定的时间间隔从Channel中读取事件。下面的例子中ticker每500毫秒触发一次,你可以观察输出的时间。 + +import ( + "fmt" + "strings" + "time" +) + +func main() { + ticker := time.NewTicker(100 * time.Millisecond) + i := 0 + for v := range ticker.C { + fmt.Printf("每隔100ms秒执行任务 %v\n", v) + i++ + if i > 10 { + break + } + } + ticker.Stop() + + fmt.Println(strings.Repeat("=", 20)) + + j := 0 + for v := range time.Tick(time.Second) { + fmt.Printf("每隔1s秒执行任务 %v \n", v) + j++ + if j > 3 { + break + } + } +} diff --git a/reuse/golang/src/package/time/timer_example.go b/reuse/golang/src/package/time/timer_example.go new file mode 100644 index 0000000..d936024 --- /dev/null +++ b/reuse/golang/src/package/time/timer_example.go @@ -0,0 +1,39 @@ +package main + +// timer是未来触发单一事件 + +// timer +// timer#Stop +// timer#Reset +// timer#C + +import ( + "fmt" + "strings" + "time" +) + +func main() { + + timer := time.NewTimer(1 * time.Second) + select { + case <-timer.C: + fmt.Println("等待1秒执行任务") + } + timer.Stop() // 这里来提高 timer 的回收 + + fmt.Println(strings.Repeat("=", 20)) + + timer2 := time.NewTimer(1 * time.Second) + i := 0 + timer2.Reset(500 * time.Millisecond) // 这样来复用 timer 和修改执行时间 + select { + case <-timer2.C: + fmt.Println("等待0.5秒执行任务") + i++ + if i > 5 { + break + } + } + timer2.Stop() +}