如何解决Golang中午运行代码?

timer.AfterFunc()time.Tick()time.Sleep()time.Ticker
time.Sleep24 *
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()
}

并且您可以将main更改为此(或您需要的任何内容):

func main() {
    go initNoon()

    // do normal task here:
    for {
        fmt.Println("do normal task here")
        time.Sleep(1 * time.Minute)
    }
}
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
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

解决方法