Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
daidai21 committed Jun 29, 2022
1 parent a955d55 commit d768e31
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
9 changes: 9 additions & 0 deletions reuse/golang/src/package/time/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

example:
go run example.go

ticker_example:
go run ticker_example.go

timer_example:
go run timer_example.go
33 changes: 33 additions & 0 deletions reuse/golang/src/package/time/ticker_example.go
Original file line number Diff line number Diff line change
@@ -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
}
}
}
39 changes: 39 additions & 0 deletions reuse/golang/src/package/time/timer_example.go
Original file line number Diff line number Diff line change
@@ -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()
}

0 comments on commit d768e31

Please sign in to comment.