2016-07-15 16 views
0

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

回答

3

所以你需要间隔定时器运行中午日常生活的一个功能,你可以使用:
time.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() 
} 

,你可能会改变主本(或者你需要的任何东西):使用time.AfterFunc

func main() { 
    go initNoon() 

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

package main 

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

func noonTask() { 
    fmt.Println(time.Now()) 
    fmt.Println("do some job.") 
    time.AfterFunc(duration(), noonTask) 
} 
func main() { 
    time.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() { 
    time.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 

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