1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
watcher.go 2.09 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-12-15 02:07 . 协程安全退出
package watcher
import (
"gitee.com/h79/goutils/common/system"
"sync/atomic"
"time"
)
type DoChanged interface {
Changed() bool
}
type Func func() bool
func (f Func) Changed() bool {
return f.Changed()
}
type Watcher struct {
stop chan bool
update chan bool
changed chan bool
method int32
ticker time.Duration
doChanged DoChanged
running system.RunningCheck
}
const (
UnkMethod = iota
NormalMethod //default
ChanMethod
)
type Option func(w *Watcher)
func NewWatcher(cha DoChanged, opts ...Option) *Watcher {
w := &Watcher{
method: UnkMethod,
doChanged: cha,
ticker: time.Second,
update: make(chan bool),
stop: make(chan bool),
}
w.UseMethod(NormalMethod)
for i := range opts {
opts[i](w)
}
return w
}
func (w *Watcher) Update() {
w.update <- true
w.run()
}
func (w *Watcher) Stop() {
system.Stop(time.Second, w.stop)
}
func (w *Watcher) UseMethod(method int32) {
oldMethod := atomic.LoadInt32(&w.method)
if oldMethod == method {
return
}
atomic.StoreInt32(&w.method, method)
if oldMethod == ChanMethod {
close(w.changed)
}
if method == ChanMethod {
w.changed = make(chan bool)
w.run()
} else if method == NormalMethod {
w.run()
}
}
func (w *Watcher) Changed() <-chan bool {
return w.changed
}
func (w *Watcher) run() {
w.running.GoRunning(func() {
ticker := time.NewTicker(w.ticker)
defer ticker.Stop()
for {
select {
case <-w.update:
if w.doChanged.Changed() && atomic.LoadInt32(&w.method) == ChanMethod {
w.changed <- true
}
case <-ticker.C:
if w.doChanged.Changed() && atomic.LoadInt32(&w.method) == ChanMethod {
w.changed <- true
}
case <-w.stop:
w.stop <- true
return
case <-system.Closed():
return
}
}
})
}
func WithTickerOption(ticker time.Duration) Option {
if ticker <= 0 {
ticker = time.Second
}
return func(w *Watcher) {
w.ticker = ticker
}
}
func WithChangedOption(changed DoChanged) Option {
return func(w *Watcher) {
w.doChanged = changed
}
}
func WithMethodOption(method int32) Option {
return func(w *Watcher) {
w.UseMethod(method)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.36

搜索帮助