zoukankan      html  css  js  c++  java
  • laravel 定时任务通过队列发送邮件

    https://www.jianshu.com/p/f6b94596098e

    关于laravel发送邮件,请先参考我的另一片文章:laravel sendcloud发送邮件,再继续往下看。

    1.用database队列驱动,生成创建这些表的迁移

    php artisan queue:table
    php artisan migrate
    

    用redis 队列驱动需要在配置文件 config/database.php 中配置 Redis 数据库连接

    2.生成任务类

    php artisan make:job SendToStarterMail
    

    生成之后,在handle方法中处理发送邮件

    <?php
    
    namespace AppJobs;
    
    use IlluminateBusQueueable;
    use IlluminateQueueSerializesModels;
    use IlluminateQueueInteractsWithQueue;
    use IlluminateContractsQueueShouldQueue;
    use IlluminateFoundationBusDispatchable;
    use IlluminateSupportFacadesLog;
    
    class SendToStarterMail implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    
        protected $email;
        /**
         * Create a new job instance.
         *
         * @return void
         */
        public function __construct($email)
        {
            $this->email = $email;
        }
    
        /**
         * Execute the job.
         *
         * @return void
         */
        public function handle()
        {
            Mail::to($useremail)->send(new StarterMail($user))//StarterMail为第3步创建的邮件类
            ->cc($moreUsers)
            ->bcc($evenMoreUsers); 
    
        }
    }
    

    3.创定时任务指令

    php artisan make:command SendStarterEmail
    

    就会在app/Console/Commands下生成一个SendStarterEmail.php文件,进入这个文件,自定义指令名:

    protected $signature = 'starter:email';
    

    添加描述

    protected $description = '创业者邀约邮件';
    

    handle方法里写逻辑

     /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            //业务逻辑
            $job = (new SendToStarterMail($email))->onConnection('database')->onQueue('emails');//SendToStarterMail为第二步生成的任务类
            dispatch($job);//分发任务到队列
        }
    

    4.设置定时时间

    在app/Console/Kernel.php的schedule方法里添加:

    protected function schedule(Schedule $schedule)
    {
         $schedule->command('starter:email')->dailyAt('12:00');
    }
    

    本地测试时,为方便测试,将执行时间改为everyMinute()运行,正式环境上线时再改回来!

    5.运行队列监听服务

    php artisan queue:work database --queue=emails #database为对接驱动,emails为队列名称,可自定义
    

    正式环境请配置在supervisor里,请参考我的另外一篇文章:supervisor 从安装到使用

    6.正式环境将以下添加如crontab中

    * * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
    

    测试环境,可运行以下代替:

    php artisan schedule:run
    
    作者:童蒙_
    链接:https://www.jianshu.com/p/f6b94596098e
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    超级强大的SVG SMIL animation动画详解
    Java Math的 floor,round和ceil的总结
    理解SVG的viewport,viewBox,preserveAspectRatio
    SVG-1
    PHP通过exec执行git pull
    Nodejs中request出现ESOCKETTIMEDOUT解决方案
    Linux安装了mysql 无法远程连接
    linux下docker启动nginx无法访问80端口
    ZPL文件打印
    k8s结合helm部署
  • 原文地址:https://www.cnblogs.com/lxwphp/p/9365805.html
Copyright © 2011-2022 走看看