登录
首页 >  Golang >  Go问答

在 Web 应用程序中运行计划任务

来源:stackoverflow

时间:2024-04-12 16:27:32 172浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《在 Web 应用程序中运行计划任务》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

我希望每 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)
}

解决方案


您的实现与 go 中的计划作业/任务非常相似。有一些类似 cron 的库可以让您更好地控制任务,但在大多数情况下,一个带有循环的简单 goroutine 就足够了。

以下是根据您的需求增加复杂性的更多示例:

永远运行一个任务,每次运行之间等待 5 秒。无法停止并且不考虑任务的运行时间。这是最简单的形式,也是最常见的形式。

go func() {
    for {
        task()
        <-time.after(5 * time.second)
    }
}()

与以前相同,只是现在有一个通道可以在我们想要的时候停止任务。虽然您的实现允许您通过 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

这是三个解决方案中最强大的解决方案。任务可以随时停止,并且它还会考虑任务在等待再次运行时所花费的时间。在前面的示例中,如果任务运行时间为 1 秒,并且您再等待 5 秒,那么相对于任务启动时的时间间隔实际上是 6 秒。

此解决方案实际上仅适用于运行时间非常长的任务,或者如果您的任务以恒定的时间间隔运行至关重要。如果任务必须以恒定的时间间隔运行,那么您需要考虑到 time.after() 将至少等待您提供的持续时间这一事实 - 如果 cpu 忙于其他任务,它最终可能会等待稍长的时间进程/协程。

// 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)
        }
    }
}()

终于介绍完啦!小伙伴们,这篇关于《在 Web 应用程序中运行计划任务》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>