laravel自定义任务队列

> php artisan make:command Dir/Example

<?php

namespace AppConsoleCommandsDir;

use IlluminateConsoleCommand;
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesRedis;

class Example extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'example';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '任务描述';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->rdb = Redis::connection();
        $this->db = DB::connection();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //启动log
        $this->setLog('beginning!~');//启动日志
        //持续运行
        while (true) {
            if (!$data = $this->getData()) {
                eval(self::BLOCK);
            }
            try {
                //核心函数
                $this->action($data);
            } catch (Exception $exception) {
                $err_msg = json_encode(['line' => $exception->getLine(), 'msg' => $exception->getMessage(), 'file' => $exception->getFile()], JSON_UNESCAPED_UNICODE);
                $this->setLog($err_msg);//录错
                eval(self::BLOCK);
            }
        }
    }

    /**
     * User:cyq
     * @param $data
     * Comment:核心函数
     */
    private function action($data){
        //逻辑操作处理
    }

    /**
     * User:cyq
     * Comment:可以根据mysql or redis 获取待处理操作的数据
     */
    private function getData()
    {
        //redis
//        return $this->rdb->rpop();
        //mysql
//        return $this->db->table()->where()->get()->toArray();
    }

    /**
     * User:cyq
     * Comment:记录操作日志
     */
    private function setLog($msg)
    {
//        LogUtil::LogDiyInfo($msg, 'Dir/exampleLog');
        //写入此类的日志文件
    }

    /** 阻塞 */
    const BLOCK = "sleep(self::SLEEP_WAIT);continue;";
    private $rdb;//redis
    private $db;//mysql
    const SLEEP_WAIT = 5;//任务列表休眠时间
}
原文地址:https://www.cnblogs.com/cyq632694540/p/14663333.html