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
发起讨论 只看当前版本


暂无话题~