2

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)
}
Mert Serin
  • 289
  • 6
  • 20
  • 4
    Why not just use a [`time.Timer`](https://golang.org/pkg/time/#Timer), or [`time.AfterFunc`](https://golang.org/pkg/time/#AfterFunc)? – JimB Mar 24 '17 at 14:48
  • I haven't seen the AfterFunc function, sorry. I edited my question with example. – Mert Serin Mar 24 '17 at 15:12
  • 2
    Just use the duration constants: `10*time.Second`, or if you want a specific time, `t.Sub(time.Now())`. – JimB Mar 24 '17 at 15:47
  • @JimB May I ask something? I'm running this code on VPS, if VPS close for some reason, my program will be terminated, so should I set these timers again or will it be executed on the right time? – Mert Serin Mar 27 '17 at 07:33

1 Answers1

3

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)
reticentroot
  • 3,612
  • 2
  • 22
  • 39