2 Star 2 Fork 8

王布衣/gox

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
rolling_mutex.go 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2024-01-22 10:36 . 这两都提示推荐使用RollingOnce
package coroutine
import (
"sync"
"sync/atomic"
"time"
)
const (
onceInitTime = "09:00:00"
onceDefaultDate = "1970-01-01"
)
// RollingMutex 按指定rolling策略加锁, 指定周期内只加载一次
//
// 滑动窗口锁, 窗口期内只初始化一次, 目前只支持1天切换
//
// Deprecated: 不推荐, 建议使用 RollingOnce
type RollingMutex struct {
m sync.Mutex
date string
done uint32
}
// 校对当前日期
func (o *RollingMutex) proofreadCurrentDate() (currentDate string) {
currentDate = o.date
if currentDate < onceDefaultDate {
currentDate = onceDefaultDate
}
now := time.Now()
timestamp := now.Format(time.TimeOnly)
if timestamp >= onceInitTime {
currentDate = now.Format(time.DateOnly)
}
return currentDate
}
func (o *RollingMutex) Do(f func(), today ...func() (newDate string)) {
getToday := o.proofreadCurrentDate
if len(today) > 0 {
getToday = today[0]
}
if getToday != nil {
currentDate := getToday()
if atomic.LoadUint32(&o.done) == 1 && currentDate > o.date {
o.doReset(currentDate)
}
}
if atomic.LoadUint32(&o.done) == 0 {
o.doSlow(f)
}
}
func (o *RollingMutex) doReset(currentDate string) {
o.m.Lock()
defer o.m.Unlock()
if o.done == 1 && currentDate > o.date {
atomic.StoreUint32(&o.done, 0)
o.date = currentDate
}
}
func (o *RollingMutex) doSlow(f func()) {
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
func (o *RollingMutex) Reset() {
atomic.StoreUint32(&o.done, 0)
}
func (o *RollingMutex) Date() string {
return o.date
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.21.2

搜索帮助