代码拉取完成,页面将自动刷新
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)
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。