4.5. 任务调度

未匹配的标注

简介#

gin-pro 任务调度基于 github.com/spf13/cobragithub.com/robfig/cron/v3 实现类似 larvel 的任务调度,你可以在 app\console\kernel 类的 Schedule 方法中定义所有的调度任务,在 Command 方法中注册需要 artisan 命令行启动的任务

定义调度任务#

定义一个调度任务非常简单只需要两步操作:

  1. 我们在 app\console\commands 文件下创建一个 print_log.go 添加以下内容
package commands

import (
    "gin-pro/app/core/system"
    "github.com/spf13/cobra"
)

func NewPrintLog() *PrintLog {
    return &PrintLog{}
}

type PrintLog struct {
    CobraCommand *cobra.Command
}

func (p *PrintLog) AddCommand() *PrintLog {
    p.CobraCommand = &cobra.Command{
        Use:   "command:PrintLog",     // 执行命令
        Short: "打印日志",              // 注释
        Run: func(cmd *cobra.Command, args []string) {
            p.Handle()
        },
    }
    return p
}

func (p *PrintLog) Handle() {
    system.ZapLog.Info("NewPrintLog print log")
}
  1. kernel.go 中注册 artisan 执行的任务,定义调度周期
package console

import (
    "gin-pro/app/console/commands"
    "gin-pro/app/core/system"
    "github.com/robfig/cron/v3"
)

func Command() {
    system.CobraCommand.AddCommand(
        commands.NewPrintLog().AddCommand().CobraCommand,
    )
}

func Schedule() {
    c := cron.New()

    //    @every 2s 每几秒执行一次
    //    支持linux crontab 命令

    c.AddFunc("@every 2s", commands.NewPrintLog().Handle)

    if system.Config.GetBool("AppDebug") == false {
        go c.Start()
        defer c.Stop()
    }
}

不需要任何外部系统级的支持即可实现定时调度任务

artisan 命令调度#

go build artisan.go 编译成功会在根目录生成 artisan 文件,执行即可实现命令调度

./artisan command:PrintLog

调度周期#

# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 查看所有版本


暂无话题~