任務隊列實現
一、 首先下載任務隊列queue類:
composer require topthink/think-queue
然后看自己的配置文件:app->config->queue.php
<?php return [ 'default' => 'database', //這里采用的是數據庫形式存儲 'connections' => [ 'sync' => [ 'type' => 'sync', ], 'database' => [ 'type' => 'database', 'queue' => 'default', 'table' => 'jobs', //表名 'connection' => null, ], 'redis' => [ 'type' => 'redis', 'queue' => 'default', 'host' => '127.0.0.1', 'port' => 6379, 'password' => '', 'select' => 0, 'timeout' => 0, 'persistent' => false, ], ], 'failed' => [ 'type' => 'none', 'table' => 'failed_jobs', ], ];
數據表:
CREATE TABLE `jobs` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `queue` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci, `attempts` tinyint(3) unsigned DEFAULT NULL, `reserve_time` int(10) unsigned DEFAULT NULL, `available_time` int(10) unsigned DEFAULT NULL, `create_time` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `zfw_jobs_queue_index` (`queue`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
二、建立任務隊列:app/job/test.php
//這里執行發送郵件 public function fire(Job $job, $data) { if ($job->attempts() > 3) { \think\facade\Log::error('Test執行失敗了'); $job->delete(); } else { // 你的數據操作 // 預約成功 發郵件通知用戶 $toemail='123123123@qq.com'; // 收件人 $name='xxxxx'; // 名稱 $subject='xxxxxx'; // 類型 $content='恭喜你'; //內容 // send_mail(); // 調用common.php中的類 SendEmail::send_mail($toemail,$name,$subject,$content); $job->delete(); } }
使用模型監聽事件添加任務到隊列中:
public static function onAfterInsert($user) {
//監聽調用模型添加的方法執行(用Db的添加方法不會執行監聽事件) Queue::later(60, 'app\job\Test', ['name'=>'test'], 'Test'); }
執行任務:
php think queue:listen --queue Test //執行隊列 nohup php think queue:listen --queue Test& //不以守護進程執行