安裝 thinkphp-queue
github : https://github.com/top-think/think-queue
composer:
composer require topthink/think-queue
報錯有可能是版本問題, 可以
composer require topthink/think-queue ^1.*
配置 extra/queue.php,我用的是redis異步,Sync則是同步
<?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' => 60, // 任務的過期時間,默認為60秒; 若要禁用,則設置為 null 'default' => 'default', // 默認的隊列名稱 'host' => '127.0.0.1', // redis 主機ip 'port' => 6379, // redis 端口 'password' => '', // redis 密碼 'select' => 0, // 使用哪一個 db,默認為 db0 'timeout' => 0, // redis連接的超時時間 'persistent' => false, ];
使用
在app下創建job目錄,建立Test.php,並編輯
<?php namespace app\job; use think\queue\job; class Test { public function fire(Job $job, $data){ if($job->attempts() > 2){ \think\Log::write('Test執行失敗'); $job->delete(); }else{ db('users')->insert([ 'username' => rand(1000,9999), ]); $job->delete(); } } }
在控制器調用
/** * 測試延時隊列 * Author : LYQ * Date : 2021/9/10 10:40 */ public function test_job() { Queue::later('10','app\job\Test',[],'Test'); //延遲十秒執行,Test為隊列名稱
Queue::push('app\job\Test',[],'Test'); //立即執行
}
監聽腳本
php think queue:listen --queue Test
效果
第一個是立即執行,第二個則是十秒后執行
了解更多 https://blog.csdn.net/will5451/article/details/80434174
踩坑,會報這個錯
不知道為啥,這個安裝,在thinkphp下,有時候會修改 /vender/composer/autoload_real.php , 紅框里面的改為require,因為tp本身已經加載一次了,這里要改為require_one
tp自動加載類在 /thinkphp/library/think/Loader.php