Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加提交一个毫秒级的定时器库 #1124

Open
zhangheli opened this issue Jul 22, 2022 · 1 comment
Open

添加提交一个毫秒级的定时器库 #1124

zhangheli opened this issue Jul 22, 2022 · 1 comment

Comments

@zhangheli
Copy link

https://github.com/zhangheli/go-ticker

go-ticker是高性能定时器库

feature
支持周期性定时器
一次性定时器
import (
"github.com/antlabs/timer"
"log"
)

func main() {
tm := timer.NewTimer()

    tm.AfterFunc(1*time.Second, func() {
            log.Printf("after\n")
    })

    tm.AfterFunc(10*time.Second, func() {
            log.Printf("after\n")
    })
    tm.Run()

}
周期性定时器
package main

import (
"fmt"
"testing"
"time"

"github.com/zhangheli/go-ticker/ticker"

)

func TestTicker(t *testing.T) {
action := func() {
fmt.Println(time.Now())
}
stopC := make(chan string, 1)

st := ticker.SecondTicker{}
st.SetPoint([]int{1, 100, 200, 300, 400, 500})
st.Run(stopC, action)

<-make(chan int, 1)

}
运行结果

2022-07-22 12:44:54.001083 +0800 CST m=+4.560425084
2022-07-22 12:44:54.100082 +0800 CST m=+4.659426001
2022-07-22 12:44:54.200079 +0800 CST m=+4.759425417
2022-07-22 12:44:54.300076 +0800 CST m=+4.859424334
2022-07-22 12:44:54.400075 +0800 CST m=+4.959425834
2022-07-22 12:44:54.500073 +0800 CST m=+5.059426042
平均 0.07 ms 误差

爆破型定时器,加特林突击
package main

import (
"fmt"
"testing"
"time"

"github.com/zhangheli/go-ticker/ticker"

)

func TestGatlin(t *testing.T) {
action := func() {
fmt.Println(time.Now())
}
now := time.Now().UnixMilli()
p := now + (1000 - now%1000)
runBegin := time.UnixMilli(p)

ticker.GatlinWithLimit(runBegin, 10, action)

}
运行效果

2022-07-22 12:50:14.000916 +0800 CST m=+0.511891751
2022-07-22 12:50:14.005861 +0800 CST m=+0.516837167
2022-07-22 12:50:14.010862 +0800 CST m=+0.521838209
2022-07-22 12:50:14.015867 +0800 CST m=+0.526842751
2022-07-22 12:50:14.020858 +0800 CST m=+0.531834667
2022-07-22 12:50:14.025865 +0800 CST m=+0.536841709
2022-07-22 12:50:14.030859 +0800 CST m=+0.541835459
2022-07-22 12:50:14.035908 +0800 CST m=+0.546884584
2022-07-22 12:50:14.040165 +0800 CST m=+0.551141667
2022-07-22 12:50:14.045885 +0800 CST m=+0.556862126
2022-07-22 12:50:14.050858 +0800 CST m=+0.561834751
误差 0.1 ~ 0.8ms 左右

@yinggaozhen
Copy link
Owner

非常感谢你的反馈~

但是目前本项目的定位是 awesome-go 的中文搬运,目前暂时无法通过在本项目添加工程。你可以前往 awesome-go 提交 Pull Requests

如果合并成功,本项目会在一天以内进行翻译 + 同步~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants