在Golang中午运行代码

Cia*_*nan 2 time automation go

是否可以每天中午执行代码?该程序正在处理用户输入剩余的运行时间,但需要在中午运行一个函数来输出一些文本.这样做最有效的方法是什么?

小智 10

所以,你需要间隔定时器运行每天中午在一个功能,你可以使用:
timer.AfterFunc()time.Tick()time.Sleep()time.Ticker

首先,当程序开始计算启动时间的时间间隔直到第一个下一个中午并使用一些等待(例如time.Sleep或......)然后使用 24 * time.Hour间隔进行下一个间隔.

示例代码使用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()
}
Run Code Online (Sandbox Code Playgroud)

你可以将main更改为this(或任何你需要的东西):

func main() {
    go initNoon()

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

使用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
Run Code Online (Sandbox Code Playgroud)

使用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  
Run Code Online (Sandbox Code Playgroud)

并参见:
https://github.com/jasonlvhit/gocron
Golang - 如何在特定时间执行函数Golang:在特定时间
实现cron /执行任务