gin 使用 crons 做定时任务: 不生效

  • 本来是想单独封装一个定时器任务 模块, 然后在main.go中调用一下启动定时器的方法,然鹅并不生效.如下:
/*
 * @Description:定时任务
 * @Author: Casso-Wong
 */

package timer

import (
    "fmt"

    "github.com/robfig/cron"
)

type storeMsg struct{}

// Run insert msg records to mysql form redis
func (s storeMsg) Run() {
    fmt.Println(123, "run")
}

// StartCron 开启定时任务程序
func StartCron() {
    c := cron.New()
    c.Start()
    defer c.Stop()
    // storeMsg := storeMsg{}
    c.AddJob("*/5 * * * * ?", storeMsg{})
}

main.go中调用 StartCron并没什么用

  • 需要在main.go中直接注册定时器:
    corns := cron.New()
    corns.Start()
    defer corns.Stop()
    corns.AddJob("*/5 * * * * ?", timer.StoreMsg{})  // 在timer包中定义的实现Run方法的结构体
  • 最终确定使用的姿势:
package jobs
import(
...
)
// Conrs 定时器
var Conrs *cron.Cron

func init() {
    Conrs = cron.New() // 定时任务
    Conrs.Start()
    Conrs.AddJob(parsecfg.GlobalConfig.Timer.Store, StoreMsg{}) // 添加定时任务
    // Conrs.AddJob(parsecfg.GlobalConfig.Timer.Store, StoreGroup{})
}

然后在 main.go中:defer jobs.Conrs.Stop()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容