当函数开始在golang中运行时如何立即执行ticker

时间:2018-01-26 11:57:10

标签: go time

我希望执行"每周更新"之前"每日检查"如下。 这意味着" time.Time"应该把" timeChan"当主要功能开始运行时,等待超过两秒后立即而不是这样做。

结果应该是这样的

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

当然,我可以打印"每周更新"首先是一次,但有一种优雅的方法?

代码如下

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
...

2 个答案:

答案 0 :(得分:2)

首先在weekly设置time.Millisecond的代码。然后在第一次完成时更改它。

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

答案 1 :(得分:1)

将工作放在一个函数中并调用它。

var a int
timeChan := time.NewTicker(time.Second * 2).C
tickChan := time.NewTicker(time.Millisecond * 500).C
f := func() {
    fmt.Println("weekly updated")
    a = 1
}
f()
for {
    select {
    case <-timeChan:
        f()
    case <-tickChan:
        if a == 1 {
            fmt.Println("daily check")
        } else {
            fmt.Println("Not update?")
        }
    }
}