dongxing4643 2017-03-24 14:31
浏览 975

在特定时间仅运行一次功能Golang

I need to set a task for specific time with Golang. For example job has ending time so I need to change some rows on table. I searched for it but I could only find periodic tasks with Cron. I don't want to set a cron to check database in every 5 minutes.

jasonlvhit has a library named gocron for Cron on Golang but I don't think It'll be useful on my problem.

Solved:

After @JimB's comment I checked the documentation of the time library and time.AfterFunc function can help me to solve this problem. After func function takes a Duration which must be nanosecond so it'll be useful if you create something like nanoSecondsToSecond()

time.AfterFunc(nanoSecondToSecond(10), func() {
    printSometing("Mert")
})

If you define a printSomething function you can call it on closure.

func printSometing(s string) {
    fmt.Println("Timer " + s)
}
  • 写回答

1条回答 默认 最新

  • dpy33121 2017-03-26 21:17
    关注

    You could try something like this. I place it in its own go routine so that it is non blocking and addition code can run below it. Often times in conjunction with a server

    ticker := time.NewTicker(5 * time.Minute)
    go func(ticker *time.Ticker) {
      for {
        select {
          case <-ticker.C:
            // do something every 5 minutes as define by the ticker above
          }
        }
    }(ticker)
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料