Running code at noon in Golang

2020-02-15 01:14发布

Is it possible to execute code at a noon everyday? The program is handling user input the rest of its run time but needs to run a function at noon to output some text. What is the most effective way to do this?

1条回答
SAY GOODBYE
2楼-- · 2020-02-15 02:08

So you need Interval Timer to run one function at noon everyday, you may use:
timer.AfterFunc() or time.Tick() or time.Sleep() or time.Ticker

first when program starts calculate time interval for start up time till first next noon and use some wait (e.g. time.Sleep or ...) then use 24 * time.Hour interval for the next interval.

sample code using time.Sleep:

package main

import "fmt"
import "time"

func noonTask() {
    fmt.Println(time.Now())
    fmt.Println("do some job.")
}
func initNoon() {
    t := time.Now()
    n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
    d := n.Sub(t)
    if d < 0 {
        n = n.Add(24 * time.Hour)
        d = n.Sub(t)
    }
    for {
        time.Sleep(d)
        d = 24 * time.Hour
        noonTask()
    }
}
func main() {
    initNoon()
}

and you may change main to this (or any thing you need):

func main() {
    go initNoon()

    // do normal task here:
    for {
        fmt.Println("do normal task here")
        time.Sleep(1 * time.Minute)
    }
}

using timer.AfterFunc:

package main

import (
    "fmt"
    "sync"
    "time"
)

func noonTask() {
    fmt.Println(time.Now())
    fmt.Println("do some job.")
    timer.AfterFunc(duration(), noonTask)
}
func main() {
    timer.AfterFunc(duration(), noonTask)
    wg.Add(1)
    // do normal task here
    wg.Wait()
}

func duration() time.Duration {
    t := time.Now()
    n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
    if t.After(n) {
        n = n.Add(24 * time.Hour)
    }
    d := n.Sub(t)
    return d
}

var wg sync.WaitGroup

using time.Ticker:

package main

import (
    "fmt"
    "sync"
    "time"
)

var ticker *time.Ticker = nil

func noonTask() {
    if ticker == nil {
        ticker = time.NewTicker(24 * time.Hour)
    }
    for {
        fmt.Println(time.Now())
        fmt.Println("do some job.")
        <-ticker.C
    }
}
func main() {
    timer.AfterFunc(duration(), noonTask)
    wg.Add(1)
    // do normal task here
    wg.Wait()
}

func duration() time.Duration {
    t := time.Now()
    n := time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, t.Location())
    if t.After(n) {
        n = n.Add(24 * time.Hour)
    }
    d := n.Sub(t)
    return d
}

var wg sync.WaitGroup  

and see:
https://github.com/jasonlvhit/gocron
Golang - How to execute function at specific times
Golang: Implementing a cron / executing tasks at a specific time

查看更多
登录 后发表回答