tp6+异步任务队列+发送邮件+模型监听

任务队列实现

注解:这里采用的以发邮件的形式。

一,
首先下载任务队列queue类:

composer require topthink/think-queue

然后看自己的配置文件:
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)
    {
//        Queue::push('','','');
        Queue::later(60, 'app\job\Test', ['name'=>'test'], 'Test');
    }
	

执行任务:

php think queue:listen --queue Test  //执行队列

nohup php think queue:listen --queue Test&   //不以守护进程执行

大功告成!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值