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

时间:2018-10-04 10:42:16

标签: 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未定义(类型* gin.Context没有字段或方法Stop)

有人能告诉我这个吗?

谢谢:)

1 个答案:

答案 0 :(得分:0)

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

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

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

更新

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