go - 如果条件为假,如何停止 golang 中的 cron 作业?

标签 go cron go-gin

我正在做一个 cron 作业来持续监控数据。在 cron 作业功能中,有一个条件我想停止 cron 作业,但我不知道如何关闭 cron 作业。以下是我正在使用的功能:-

CronController.go

 func AutomaticChargedCron(c *gin.Context) {
     err:= //there is function which gives the value to err 
     if err != nil {
        fmt.Println("There is something wrong please try again later.", err)     
        //I want to stop the cron here
     } 
 }  

cron.go

package cron

import (
    "gopkg.in/robfig/cron.v2"
)
func RunCron() {
    c := cron.New()

    c.AddFunc("@every 0h10m0s", AutomaticChargedCron)
    c.Start()
}

func AutomaticChargedCron() {
    utils.ExecuteCommand("sh " + config.GetBasePath() + "sh/charged.sh") 
}

charged.sh

 curl "http://localhost:8080/api/v1/charged"

Router.go

 func main() {
   router := gin.Default()

   router.GET("/charged", controllers.AutomaticChargedCron)

   router.Run()
   router.Run(":8080") 
}

我使用了 c.Stop() 但给出了错误

c.Stop undefined (type *gin.Context has no field or method Stop)

谁能告诉我这件事。

谢谢:)

最佳答案

这是因为变量名 c 被使用了两次,一次用于 cron 作业,另一次作为处理函数内的 *gin.Contex

它可以通过简单的变量重命名来缓解。

cr := cron.New()
# and rename all occurrence of cron `c` as `cr`
cr.Stop()

更新

仅当您尝试在使用 (c *gin.Contex) 的处理函数中使用 cron c 时,才需要重命名。函数参数中的 c 隐藏了全局 cron c

关于go - 如果条件为假,如何停止 golang 中的 cron 作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52644739/

相关文章:

algorithm - Golang 代码对于 Hackerrank 来说太慢了

json - 定义结构并将其编码为 json 的问题

go - 如何在无限 for 循环中实现 goroutine; for{} 在 WaitGroup 完成后重试?

php - 使用 PHP 创建、编辑和删除 crontab 作业?

linux - 如何在凌晨 1 点到凌晨 2 点每 5 分钟执行一次 cron

go - 当服务器因 gin-gonic 和 gin-contrib/gzip 而崩溃时,HTTP 客户端收到状态码 200

go - 当我重定向初始请求时如何在 Gin 中记录响应正文

testing - 去基准和 gc : B/op alloc/op

postgresql - 创建新结构并将其附加到一对多关系中的数组

python - 使用 cron 终止后运行程序