首页 > 解决方案 > 使用默认时间调用 func Golang

问题描述

我的 func 开始。然后在 2 分钟后再次运行。如何在凌晨 3 点再次运行?我用户时间。打勾

func doEvery(d time.Duration, f func(time.Time)) {
    for x := range time.Tick(d) {
        f(x)
    }
}
func RunUpdateTimeTable(respond chan<- string) {
    respond <- "Start get timetables info service."
    updateTimeTables(time.Now())
    doEvery(2*time.Minute, updateTimeTables)
}

标签: gotime

解决方案


这里是

func doAtEvery3am(f func(time.Time)) {
    for {
        // compute duration until 3am local time
        t := time.Now()
        t = time.Date(t.Year(), t.Month(), t.Day(), 3, 0, 0, 0, time.Local)
        d := time.Until(t)
        if d <= 0 {
            d = time.Until(t.Add(24*time.Hour))
        }
        // wait duration and call f
        f(<-time.After(d))
    }
}

注意:我们在执行后重新计算持续时间到凌晨 3 点,f因为执行持续时间f是未知的。


推荐阅读