golang 定时器实现方法 NewTimer及NewTicker
package Timer
import (
"fmt"
"sync"
"time"
)
type TimerTicket struct {
wg sync.WaitGroup
second int //定时执行时间
replay int //重试次数
}
func NewTimerTicket(second int) *TimerTicket {
return &TimerTicket{second: second}
}
func (t *TimerTicket) Run() {
notice:="定时器开始执行\n间隔执行时间:%d秒\n执行最大次数:%d\n"
fmt.Printf(notice, t.second, t.replay)
defer func() {
fmt.Println("整体定时器结束")
}()
t.wg.Add(2)
go t.ticket()
go t.timer()
t.wg.Wait()
}
//使用ticket实现
func (t *TimerTicket) ticket() {
replay:=t.replay
ticket := time.NewTicker(time.Second * time.Duration(t.second))
defer func() {
t.wg.Done()
fmt.Println("ticket 结束了")
}()
Loop:
for {
select {
case <-ticket.C:
fmt.Println("开始执行 ticket", time.Now(), "replay", replay)
replay += 1
if replay >= 5 {
ticket.Stop()
break Loop
}
}
}
}
//使用timer实现
func (t *TimerTicket) timer() {
replay:=t.replay
ticker := time.NewTimer(time.Duration(t.second) * time.Second)
defer func() {
fmt.Println("timer 结束了")
t.wg.Done()
}()
Loop:
for {
select {
case <-ticker.C:
fmt.Println("开始执行 timer", time.Now(), "replay", replay)
replay += 1
if replay >= 5 {
ticker.Stop()
break Loop
} else {
ticker.Reset(time.Duration(t.second) * time.Second)
}
}
}
}
本文地址:https://blog.csdn.net/riou00/article/details/109011414
上一篇: 强化学习基本内容 人工智能机器学习
下一篇: 机器学习及其应用2007