How to make an Endless Ticker in golang ?

polaris · · 531 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>What is the good way to make a endless ticker in golang ? I would like to perform an action each 30 seconds in my program</p> <p>regards and thanks</p> <hr/>**评论:**<br/><br/>TheMerovius: <pre><p><a href="https://godoc.org/time#NewTicker" rel="nofollow">Like this</a></p></pre>WellAdjustedOutlaw: <pre><p>Is there a reason you can&#39;t use an endless for {} with a sleep for 30 seconds? Do you specifically need the semantics of a ticker?</p> <p>If you actually need the semantics of a ticker, you&#39;d just have an endless for loop and select from the ticker&#39;s channel. This would cause the loop to block waiting for the channel.</p> <p>Either way, you need to make sure that what you want isn&#39;t a minimum 30s delay after your work is completed, and instead a timer that will tick every 30s but will skip missed ticks. So if your work takes 29 seconds to run, it will run again in 1 second. And if it takes 31 seconds the timer will tick again in 29 seconds.</p></pre>UniverseCity: <pre><p>In the case of the former you should use <a href="https://golang.org/pkg/time/#Tick" rel="nofollow">time.Tick</a></p></pre>relvae: <pre><p>Doesn&#39;t tick block until the tick is received? If it takes 31 seconds the next iteration would start immediately. </p> <p>Edit: nvm I looked at the source and you are right NewTicker does drop messages for slow receivers</p></pre>WellAdjustedOutlaw: <pre><p>Yeah, I stumbled on it accidentally which is the only reason I knew.</p></pre>PacNinja: <pre><p>Can use Ticker in time package. Example: <a href="https://gobyexample.com/tickers" rel="nofollow">https://gobyexample.com/tickers</a></p></pre>imroc: <pre><p>for range time.Tick(30*time.Second) { ...... }</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

531 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传