1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
api
auth
common
algorithm
app
attributes
banner
bus
coder
compress
config
daemon
data
debug
file
filemgr
git
http
images
json
list
logger
mapper
perf
queue
random
result
scheduler
secret
server
ssh
stringutil
svc
system
template
timer
expire.go
tick.go
timer.go
timer_test.go
trie
version
xml
bit_flag.go
common.go
common_test.go
integer.go
recover.go
dao
discovery
loader
mq
pay
plugins
report
request
rpc
sensitive
thrift
.gitignore
LICENSE
Makefile
README.md
doc.go
error.md
go.mod
go.sum
goutils.go
goutils_test.go
version.go
克隆/下载
tick.go 1.31 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2年前 . recover
package timer
import (
"errors"
"gitee.com/h79/goutils/common"
"time"
)
var (
TimeoutError = errors.New("operation timed out")
)
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
}
go func() {
defer common.Recover()
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
}
}
}
}()
}
func Call(timeout time.Duration, fn func() (interface{}, error)) (interface{}, error) {
if timeout > 0 {
resultCh := make(chan *resultWithError, 1)
go func() {
defer common.Recover()
result, err := fn()
resultCh <- &resultWithError{result, err}
}()
select {
case <-time.After(timeout):
return nil, TimeoutError
case rwe := <-resultCh:
return rwe.result, rwe.err
}
}
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.3.48

搜索帮助