-1

My func start .Then run again after 2 min . How to func run again at 3 am ? I user time.Tick

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)
}
Doctor Strange
  • 37
  • 1
  • 2
  • 10

2 Answers2

1

Here it is

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))
    }
}

Note: we recompute the duration to 3am after executing f because the execution duration of f is unknown.

chmike
  • 20,922
  • 21
  • 83
  • 106
  • thanks @chimike . My question seems is here : [https://stackoverflow.com/questions/38386762/running-code-at-noon-in-golang] – Doctor Strange Dec 19 '19 at 09:58
  • @DoctorStrange it’s not exactly the same. The answer you referred to is not recomputing the duration after the execution of `f`. It simply waits 24h after the execution of `f`. As a consequence, the execution time will drift due to the execution duration of `f`. In my solution, I recompute the duration to 3am after the execution of `f`. The execution duration may be long. My computation of the duration to wait is also simpler. Apart from that, the solutions are indeed very similar. – chmike Dec 19 '19 at 10:03
  • @chimike . I testing to find difference its . Thanks you so much – Doctor Strange Dec 19 '19 at 10:10
0

Not a nice solution, but works.

func doEveryDay(h int, f func(time.Time)) {

    now := time.Now()
    if now.Hour() > h {
        now.Add(time.Hour * 24)
    }

    d := time.Millisecond * 900

    for tick := range time.Tick(d) {
        if now.Day() == tick.Day() && tick.Hour() == h && tick.Minute() == 0 && tick.Second() == 0 {
            f(tick)
            now.Add(time.Hour * 24)
        }
    }
}
p1gd0g
  • 631
  • 5
  • 16