【问题标题】:How to stop the cron job in golang while if condition is false?如果条件为假,如何在golang中停止cron作业?
【发布时间】:2018-10-05 02:02:58
【问题描述】:

我正在做一个 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(类型*gin.Context没有Stop字段或方法)

谁能告诉我这个。

谢谢:)

【问题讨论】:

    标签: go cron go-gin


    【解决方案1】:

    这是因为变量名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

    【讨论】:

    • c *gin.Context 变量不是 AutomaticChargedCron 函数的本地变量,即它不应该与 cron 初始化勾结,还是我错过了什么?
    • yes cAutomaticChargedCron 函数的本地变量,您正试图在同一函数 c 内使用同一变量 c 停止 cron,因此它将使用 *gin.Context @ 987654335@ 不是 cron c
    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 2015-07-30
    • 2018-05-02
    • 2019-12-17
    • 2023-03-06
    • 2013-10-22
    • 1970-01-01
    • 2011-05-28
    相关资源
    最近更新 更多