任务队列实现
一、 首先下载任务队列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& //不以守护进程执行