1 Star 0 Fork 0

Souki/go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
support_rate.go 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
sage 提交于 2023-04-26 16:35 +08:00 . optimize stop worker
package comag
import (
v1log "gitee.com/scottq/go-framework/src/v1/log"
"math"
"time"
)
type CtlRater struct {
StopNotifyWorker
Do func()
Rate int64
v1log.InvokeLog
ch chan int
}
func (ctl *CtlRater) Start() {
defer ctl.Info("do by rate stopped")
if ctl.ch == nil {
ctl.ch = make(chan int, 64)
}
if ctl.Rate <= 0 {
ctl.Rate = 1
}
go ctl.ctlRate()
ctl.start()
}
func (ctl *CtlRater) start() {
ctl.Info("ctl rate start work")
do := ctl.Do
for {
select {
case num, ok := <-ctl.ch:
if !ok {
return
}
if num <= 0 {
continue
}
if do != nil {
for i := 1; i <= num; i++ {
do()
}
}
ctl.Info("do success %d, func is %t", num, do != nil)
case <-ctl.StopNotify():
return
}
}
}
func (ctl *CtlRater) ctlRate() {
interval := time.Millisecond * 100 //单次执行间隔
ti := time.NewTicker(interval)
add := float64(ctl.Rate) / float64(time.Second/interval) //每次间隔增加的值
var x float64 = 0
ctl.Debug("ctl rate will do every %s, every %.3f", interval, add)
for {
select {
case <-ti.C:
num := math.Floor(x + add)
x = x + add - num
ctl.ch <- int(num)
case <-ctl.StopNotify():
return
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.46

搜索帮助