<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 (
"fmt"
"time"
)
func logsleep(tick time.Time) {
fmt.Println("Tick at", 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'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 (
"fmt"
"time"
)
func logsleep(tick time.Time) {
fmt.Println("Tick at", 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'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's constant, you are fine. If it's slow because it's max'ing out IO then it'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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传