1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
tick.go 1.43 KB
一键复制 编辑 原始数据 按行查看 历史
package timer
import (
"errors"
"gitee.com/h79/goutils/common/system"
"time"
)
var (
TimeoutError = errors.New("operation timed out")
ClosedError = errors.New("process closed")
)
type CallbackFunc func(interface{}) bool
// Ticker
// 定时调用
func Ticker(tick time.Duration, fun CallbackFunc, param interface{},
funcDefer CallbackFunc, paramDefer interface{}) {
Delay(0, tick, fun, param, funcDefer, paramDefer)
}
func Delay(delay, tick time.Duration, fun CallbackFunc, param interface{},
funcDefer CallbackFunc, paramDefer interface{}) {
if fun == nil {
return
}
system.ChildRunning(func() {
defer func() {
if funcDefer != nil {
funcDefer(paramDefer)
}
}()
if delay > 0 {
time.Sleep(delay)
if fun(param) {
return
}
}
ticker := time.NewTicker(tick)
for {
select {
case _ = <-ticker.C:
if fun(param) {
return
}
case <-system.Closed():
return
}
}
})
}
func Call(timeout time.Duration, fn func() (interface{}, error)) (interface{}, error) {
if timeout > 0 {
resultCh := make(chan *resultWithError, 1)
system.ChildRunning(func() {
result, err := fn()
resultCh <- &resultWithError{result, err}
})
select {
case <-time.After(timeout):
return nil, TimeoutError
case rwe := <-resultCh:
return rwe.result, rwe.err
case <-system.Closed():
return nil, ClosedError
}
}
return fn()
}
type resultWithError struct {
result interface{}
err error
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.8.33

搜索帮助