在Golang中只运行一次特定时间的函数。

huangapple go评论91阅读模式
英文:

Run function only once for specific time Golang

问题

我需要使用Golang在特定时间设置一个任务。例如,任务有一个结束时间,所以我需要在表格上更改一些行。我搜索了一下,但只找到了使用Cron进行周期性任务的方法。我不想设置一个Cron来每5分钟检查数据库。

jasonlvhit有一个名为gocron的库,用于在Golang中使用Cron,但我不认为它对我的问题有用。

解决方案:

在@JimB的评论后,我查看了时间库的文档,发现time.AfterFunc函数可以帮助我解决这个问题。AfterFunc函数接受一个持续时间(Duration),它必须是纳秒,所以如果你创建一个类似nanoSecondsToSecond()的函数,它会很有用。

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

如果你定义了一个printSomething函数,你可以在闭包中调用它。

func printSometing(s string) {
    fmt.Println("Timer " + s)
}
英文:

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

得分: 3

你可以尝试这样做。我将它放在自己的go例程中,以便它是非阻塞的,并且可以在其下运行其他代码。通常与服务器一起使用。

ticker := time.NewTicker(5 * time.Minute)
go func(ticker *time.Ticker) {
  for {
    select {
      case <-ticker.C:
        // 每5分钟执行一次操作,由上面的ticker定义
    }
  }
}(ticker)
英文:

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 &lt;-ticker.C:
	    // do something every 5 minutes as define by the ticker above
	  }
	}
}(ticker)

huangapple
  • 本文由 发表于 2017年3月24日 22:31:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/43002163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定