gpt4 book ai didi

go - golang中函数开始运行时如何立即执行ticker

转载 作者:IT王子 更新时间:2023-10-29 01:57:17 26 4
gpt4 key购买 nike

我希望在“每日检查”之前执行“每周更新”,如下所示。这意味着“time.Time”应该立即放置“timeChan”,而不是在主函数开始运行时等待超过两秒后才执行。

结果应该是这样的

weekly updated
daily check
daily check
daily check
daily check
weekly updated
daily check
daily check
daily check
daily check
...

当然,我可以只打印一次“weekly updated”,但是有什么优雅的方法吗?

代码如下

package main

import "time"
import "fmt"

func main() {
var a int
timeChan := time.NewTicker(time.Second * 2).C

tickChan := time.NewTicker(time.Millisecond * 500).C

for {
select {
case <-timeChan:
fmt.Println("weekly updated")
a = 1
case <-tickChan:
if a == 1 {
fmt.Println("daily check")
} else {
fmt.Println("Not update?")
}
}
}
}

结果如下

Not update?
Not update?
Not update?
weekly updated
daily check
daily check
daily check
daily check
weekly updated
daily check
daily check
daily check
daily check
...

最佳答案

在第一个 time.Millisecond 将您的代码设置为 weekly。然后在第一次完成时更改它。

package main

import (
"fmt"
"time"
)

func main() {
var a = 0

ticker := time.NewTicker(1)
timeChan := ticker.C
tickChan := time.NewTicker(time.Millisecond * 500).C

for {
select {
case <-timeChan:
fmt.Println("weekly updated")
if a == 0 {
ticker.Stop()
timeChan = time.NewTicker(time.Second * 2).C
}
a = 1
case <-tickChan:
if a == 1 {
fmt.Println("daily check")
} else {
fmt.Println("Not update?")
}
default:
}
}
}

输出:

weekly updated
daily check
daily check
daily check
daily check
weekly updated

关于go - golang中函数开始运行时如何立即执行ticker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48460922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com