think\queue\Job` 类来执行队列任务

文章介绍了如何在ThinkPHP5框架中使用队列任务,包括创建自定义任务类,如TestJob,实现fire方法并在其中编写任务逻辑和打印结果。通过`phpthinkqueue:work`命令执行队列,同时展示了队列配置如使用Redis驱动,以及如何在控制器中推送任务到队列。此外,还给出了LogJob类作为另一个任务示例,处理日志插入数据库并根据结果决定是否重新发布任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

thinkphp5 中,使用 think\queue\Job 类来执行队列任务,可以在命令行中打印执行结果。可以在 app\queue\job 目录下创建一个继承 think\queue\Job 的任务类,然后在任务类中实现 fire 方法,该方法就是任务的执行方法。在 fire 方法中,可以编写任务的具体逻辑,执行完成后可以在命令行中打印执行结果。

例如,创建一个任务类 app\queue\job\TestJob.php,代码如下:

<?php

namespace app\queue\job;

use think\queue\Job;

class TestJob
{
    public function fire(Job $job, $data)
    {
        // 执行任务逻辑
        $result = $this->doSomething($data);

        // 执行完成后打印结果
        echo '任务执行结果:' . $result . PHP_EOL;

        // 执行完成后删除任务
        $job->delete();
    }

    private function doSomething($data)
    {
        // 执行具体的任务逻辑
        return '任务执行成功';
    }
}

然后在命令行中执行队列任务,例如:

php think queue:work --queue test

其中 test 是队列名称,执行完成后会在命令行中打印任务执行结果。




```bash
  public function testJob3()
    {
        // 推送任务到队列
        $jobHandlerClassName = 'app\job\TestJob3'; // 任务处理类
        $jobData = ['name' => 'test']; // 任务数据
        $queueName = 'TestJob3'; // 队列名称
        Queue::push($jobHandlerClassName, $jobData, $queueName);
        // $d =  Queue::push($jobHandlerClassName, $jobData, $queueName);
        // exit;
    }

例子2: thinkphp5.0 队列的配置

application\extra\queue.php
queue.php文件如下

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------

return [
    'connector' => 'Redis',            // Redis 驱动
    'expire' => 120,                // 任务的过期时间,默认为60秒; 若要禁用,则设置为 null
    'default' => 'default',        // 默认的队列名称
    'host' => '127.0.0.1',        // redis 主机ip
    'port' => 6379,            // redis 端口
    'password' => '',                // redis 密码
    'select' => 1,                // 使用哪一个 db,默认为 db0
    'timeout' => 0,                // redis连接的超时时间
    'persistent' => false,
];

composer 中文件如下

{
    "name": "topthink/think",
    "description": "the new thinkphp framework",
    "type": "project",
    "keywords": [
        "framework",
        "thinkphp",
        "ORM"
    ],
    "homepage": "http://thinkphp.cn/",
    "license": "Apache-2.0",
    "authors": [
        {
            "name": "liu21st",
            "email": "liu21st@gmail.com"
        }
    ],
     "repositories": {
    	"packagist": {
        	"type": "composer",
        	"url": "https://packagist.phpcomposer.com"
    	}
	},
    "require": {
        "php": ">=5.4.0",
        "topthink/framework": "^5.0",
        "topthink/think-image": "^1.0",
        "topthink/think-captcha": "^1.0",
        "topthink/think-mongo": "^1.0",
        "topthink/think-migration": "^1.0",
        "topthink/think-angular": "^1.0",
        "topthink/think-sae": "^1.0",
        "topthink/think-worker": "^1.0",
        "topthink/think-queue": "^1.0",
        "topthink/think-testing": "^1.0",
      "ext-json": "*"
    },
    "extra": {
        "think-path": "thinkphp"
    },
    "config": {
        "preferred-install": "dist"
    }
}

队列1: application\job\JobTest1.php, 队列2: application\job\LogJob.php
JobTest1.php 如下

<?php
namespace app\job;
use think\Db;
use think\queue\Job;

/**
 * Created by PhpStorm.
 * User: wangkaixin
 * Email: 2548880572@qq.com
 * Date: 2023/9/13 013
 * Time: 19:12
 */

class JobTest1
{
    public function fire(Job $job, $data)
    {
        // 执行任务逻辑
        $result = $this->doSomething($data);
        var_dump($data);
        // 执行完成后打印结果
        echo '任务执行结果:' . $result . PHP_EOL;

        // 执行完成后删除任务
        $job->delete();
    }

    public function doSomething($data)
    {
        Db::name('queue_log')->insert([
            'no' => '3434343',
            'emp_name' => 'dd',
            'dingding_id' => '23232',
            'status' => 'status'
        ]);
        // 执行具体的任务逻辑
        return '任务执行成功';
    }
}

LogJob.php 如下

<?php

namespace app\job;

use think\queue\Job;
use think\Db;

class LogJob
{
    public function fire(Job $job, $data)
    {
        // Execute the logic for inserting the log into the database
        $result = $this->insertLog($data);

        if ($result) {
            // If the log insertion is successful, delete the job from the queue
            $job->delete();
            echo 'Log inserted successfully.' . PHP_EOL;
        } else {
            // If the log insertion fails, release the job back to the queue with a delay of 3 seconds
            $job->release(3);
            echo 'Failed to insert log. Job will be retried.' . PHP_EOL;
        }
    }

    public function insertLog($data)
    {

        // Perform the actual logic to insert the log into the database
        try {
            Db::name('queue_log')->insert([
                'emp_name' => $data['content'],
                'time' => time(),
            ]);

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}

在控制器中执行, application\index\controller\Index.php

<?php
namespace app\index\controller;

use think\Db;
use think\Log;
use think\Queue;
use app\job\LogJob;

class Index
{
    public function index()
    {
        // 推送任务到队列
        $jobHandlerClassName = 'app\job\JobTest1'; // 任务处理类
        $jobData = ['name' => 'test']; // 任务数据
        $queueName = 'JobTest1'; // 队列名称
        $queueId = Queue::push($jobHandlerClassName, $jobData, $queueName);
        echo $queueId;


        // Dispatch the job to the default queue
        $queueId = Queue::push(LogJob::class, ['content' => 'test'], 'LogJob');
        echo $queueId;
        return 'index';
    }
}

在phpstorm或者cmd目录中对应项目目录中 执行 php think queue:listen --queue LogJob; php think queue:listen --queue JobTest1 或者 命令 php think queue:work–queue LogJob; php think queue:work–queue JobTest1

然后刷新 页面 执行 index 控制器 ,

array(1) {
  'name' =>
  string(4) "test"
}
任务执行结果:任务执行成功
Processed: app\job\LogJob
Log inserted successfully.
Processed: app\job\LogJob
Log inserted successfully.
Processed: app\job\LogJob
Log inserted successfully.
Processed: app\job\LogJob

在这里插入图片描述

PS: 记录一次终端中执行 php think 无效的情况 thinkphp\console.php, 结果是测试服上的项目中 thinkphp中缺少console.php, 执行php think 无任何反应,拷贝正常的项目中的 console.php 到对应目录即可

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值