我想每 5 分钟运行一次任务来更新我网站上的统计信息,而不会阻止 HTTP 服务器。
我刚刚添加了基本的 HTTP 服务器逻辑和一个工作程序示例。如果我添加了多个这样的任务,这被认为是不好的做法还是有更好的方法?
package main
import (
"fmt"
"net/http"
"time"
)
func Home(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Home page")
}
func schedule(f func(), interval time.Duration) *time.Ticker {
ticker := time.NewTicker(interval)
go func() {
for range ticker.C {
f()
}
}()
return ticker
}
func longRunningTask() {
fmt.Println("Long running task")
}
func main() {
schedule(longRunningTask, time.Second*5)
http.HandleFunc("/", Home)
http.ListenAndServe("127.0.0.1:8080", nil)
}
Run Code Online (Sandbox Code Playgroud)
您的实现与 Go 中的预定作业/任务非常相似。有一些 cron-esque 库可以让你更好地控制任务,但在大多数情况下,一个简单的带有循环的 goroutine 就足够了。
以下是根据您的需求增加复杂性的更多示例:
永远运行任务,每次运行之间等待 5 秒。无法停止并且不考虑任务的运行时间。这是最简单的形式,也是最常见的形式。
go func() {
for {
task()
<-time.After(5 * time.Second)
}
}()
Run Code Online (Sandbox Code Playgroud)
和以前一样,除了现在有一个通道可以停止任务。虽然您的实现允许您通过Stop()
方法停止任务,但 goroutine 将保持打开状态,因为通道永远不会关闭(因此会泄漏内存)。
// Includes a channel to stop the task if needed.
quit := make(chan bool, 1)
go func() {
task()
for {
select {
case <-quit:
return
case <-time.After(5 * time.Second):
task()
}
}
}()
// To stop the task
quit <- true
Run Code Online (Sandbox Code Playgroud)
这是三者中最强大的解决方案。任务可以在任何时候停止,它还考虑了任务在等待再次运行时运行的时间。在前面的示例中,如果任务运行时间为 1 秒,而您又等待了 5 秒,则相对于任务启动时间,您的间隔实际上是 6 秒。
此解决方案确实仅适用于运行时间非常长的任务,或者您的任务以恒定时间间隔运行至关重要。如果任务必须以恒定的时间间隔运行,那么您需要考虑这样一个事实,即time.After()
至少等待您提供的持续时间——如果 CPU 忙于其他进程/goroutine,它最终可能会等待稍长一些。
// Calls `fn` and then waits so the total elapsed time is `interval`
func runAndWait(interval time.Duration, fn func()) {
earlier := time.Now()
fn()
diff := time.Now().Sub(earlier)
<-time.After(interval - diff)
}
quit := make(chan bool, 1)
go func() {
// The total time to run one iteration of the task
interval := 5 * time.Second
for {
select {
case <-quit:
return
default:
runAndWait(interval, task)
}
}
}()
Run Code Online (Sandbox Code Playgroud)