我正在做一个用于连续监控数据的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.停止未定义(类型 *gin.上下文没有字段或方法 停止(
谁能告诉我这个。
谢谢:)
这是因为变量名c
被使用了两次,一次用于 cron 作业,另一次用于处理程序函数中的*gin.Contex
。
可以通过简单的变量重命名来缓解它。
cr := cron.New()
# and rename all occurrence of cron `c` as `cr`
cr.Stop()
更新
仅当您尝试在使用(c *gin.Contex)
的处理程序函数中使用 cronc
时,才需要重命名。函数参数中的c
隐藏全局 cronc
。