-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} |