Run function every x seconds

xuanbao · · 326 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I want to run a function every second, but that function may take more than the second between iterations. For example:</p> <pre><code>package main import ( &#34;fmt&#34; &#34;time&#34; ) func logsleep(tick time.Time) { fmt.Println(&#34;Tick at&#34;, tick) time.Sleep(5 * time.Second) } func main() { ticker := time.NewTicker(1 * time.Second) go func() { for t := range ticker.C { logsleep(t) } }() for { } } </code></pre> <p>I want <code>logsleep</code> to be called every second, but what&#39;s happening is the <code>sleep</code> is taking 5 seconds and delays the next call to <code>logsleep</code>. Is this possible?</p> <hr/>**评论:**<br/><br/>MalkMalice: <pre><p>You could do something like this:</p> <pre><code>package main import ( &#34;fmt&#34; &#34;time&#34; ) func logsleep(tick time.Time) { fmt.Println(&#34;Tick at&#34;, tick) time.Sleep(5 * time.Second) } func main() { for t := range time.Tick(1 * time.Second) { go logsleep(t) } } </code></pre> <p>But I don&#39;t understand what you try to achieve. If the loogsleep function takes longer than one second all the time, the app will run ut of resources at some point.</p></pre>nevyn: <pre><blockquote> <p>If the logsleep function takes longer than one second all the time, the app will run out of resources at some point</p> </blockquote> <p>As long as it&#39;s constant, you are fine. If it&#39;s slow because it&#39;s max&#39;ing out IO then it&#39;ll get worse, which will be bad.</p></pre>forfunc: <pre><p>See <a href="https://golang.org/pkg/time/#AfterFunc" rel="nofollow">https://golang.org/pkg/time/#AfterFunc</a> I think this is what you need for your use case with some usefull additions that you can stop the call if it takes to long</p></pre>

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

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