我正在做一个 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/