先使用 time.AfterFunc,再启动 time.NewTicker
时间:2024-03-04
浏览:416
作者:佚名
一分耕耘,一分收获!既然都打开这篇《先使用 time.AfterFunc,再启动 time.NewTicker》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
我正在尝试设置一个每小时运行的服务例程。在我看来,这两个都很容易。要在整点运行我的例程,我可以使用 time.afterfunc(),首先计算到整点的剩余时间。为了每小时运行我的例程,我可以使用 time.newticker()。
但是,我很难弄清楚如何仅在传递给 afterfunc() 的函数触发后才启动 newticker。
我的 main() 函数看起来像这样:
func main() {
fmt.println("starting up")
// here i'm setting up all kinds of http listeners and grpc listeners, none
// of which is important, save to mention that the app has more happening
// than just this service routine.
// calculate duration until next hour and call time.afterfunc()
// for the purposes of this exercise i'm just using 5 seconds so as not to
// have to wait increments of hours to see the results
time.afterfunc(time.second * 5, func() {
fmt.println("afterfunc")
})
// set up a ticker to run every hour. again, for the purposes of this
// exercise i'm ticking every 2 seconds just to see some results
t := time.newticker(time.second * 2)
defer t.stop()
go func() {
for now := range t.c {
fmt.println("ticker")
}
}()
// block until termination signal is received
ossignals := make(chan os.signal, 1)
signal.notify(ossignals, syscall.sigint, syscall.sigterm, os.interrupt, os.kill)
<-ossignals
fmt.println("exiting gracefully")
}
当然,time.afterfunc() 是阻塞的,并且我的 ticker 的有效负载是故意放入 go 例程中的,因此它也不会阻塞。这样我的 http 和 grpc 侦听器可以继续侦听,但也允许 main() 末尾的代码块在收到操作系统的终止信号时正常退出。但现在明显的缺点是 ticker 几乎立即启动,并在传递给 afterfunc() 的函数触发之前触发两次(2 秒间隔)。输出如下所示:
ticker ticker afterfunc ticker ticker ticker etc.
我想要的当然是:
afterfunc ticker ticker ticker ticker ticker etc.
以下内容也不起作用,我不确定为什么。它打印 afterfunc 但 ticker 从不触发。
time.AfterFunc(time.Second * 5, func() {
fmt.Println("AfterFunc")
t := time.NewTicker(time.Second * 2)
defer t.Stop()
go func() {
for now := range t.C {
fmt.Println("Ticker")
}
}()
})
解决方案
time.afterfunc(time.second*5, func() {
fmt.println("afterfunc")
t := time.newticker(time.second * 2)
defer t.stop()
for range t.c {
fmt.println("ticker")
}
})
它会产生您需要的输出:
starting up afterfunc ticker ticker ticker ticker ticker
time.AfterFunc(time.Second * 5, func() {
fmt.Println("AfterFunc")
t := time.NewTicker(time.Second * 2)
defer t.Stop()
go func() {
for now := range t.C {
fmt.Println("Ticker")
}
}()
})
defer t.stop() 停止滚动条。
你没有等待 goroutine 运行。
本篇关于《先使用 time.AfterFunc,再启动 time.NewTicker》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
