Laravel5.6 사용은 타이밍 메일을 달성하기 위해 예약 된 작업을

이 문서는 작업 스케줄링 Laravel 달성을 지원하기 위해 리눅스의 crontab 예약 된 작업을 사용하는 것입니다

첫째, 프로젝트를 생성

1. 단말기의 명령을 실행 laravel new crontab하여 데이터베이스를 포함하여, 그 지역의 정상적인 작동을 보장하기 위해. 그 후 라인에 배치했다. phpstrom서버에 연결 코드가 제대로 서버로 전송 될 수 있는지 확인합니다.
: 2, 작업 유형을 작성, 터미널은 명령을 실행 php artisan make:command SendEmail
수정 3 SendEmail.php파일을

protected $signature = 'email:send';
protected $description = '定时发邮件测试';

다음과 같이 4, 최초의 전자 메일, 파일의 현재 시간을 쓰기 먼저 테스트 파일을 작성하는 타이밍에, 당황하지 말고

public function handle()
{
  //写入文件
  file_put_contents("/var/www/crontab/file.txt", date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
}

참고 : PHP_EOL시간 목록 랩을 나타낸다는, 후자는 FILE_APPENDAPPEND 다시 기록을 의미합니다.

5 수정 app/Console/Kernel.php파일 :

protected $commands = [
    Commands\SendEmail::class //注册任务类
];

protected function schedule(Schedule $schedule)
{
	//每分钟执行一次文件的写入
    $schedule->command('email:send')
        ->everyMinute();
}

6, 서버, 프로젝트에 : cd /var/www/crontab먼저 서버 점검 PHP, 설치 경로를 명령 실행 : which phpPHP경로를 /usr/bin/php다음 경로 아래로 복사본을 저장 한 다음 명령을 실행 crontab -e열기를 선택, 처음 네 개의 권장 사항을 선택합니다. 마지막 줄에 다음 코드를 추가합니다 :

* * * * * /usr/bin/php /var/www/crontab/artisan schedule:run >> /dev/null 2>&1

참고 : 다음은 전면 부 /usr/bin/php서버 대신 PHP설치 경로, 대표 프로젝트 디렉토리의 뒤쪽 부분.
또한 오 별표 위의 명령 앞에 * 분, 시간, 일, 월, 주를 나타냅니다.
최소 : 정수, 기본 별표 1 분 동안 별표 0-59 / 1.
시간 : 0-23의 정수입니다.
주 : 정수 1-31.
달 : 정수 1-12.
주 : 0-7, 0과 7은 일요일을 나타내는 정수.
crontab을 -l은 현재 예약 된 작업을 나열합니다.

7, 작업 시작 sudo service cron restart열고, FZ루트 서버 프로젝트에서 뷰를 file.txt기록 파일에 시간이 있으면 모든 분을 실행합니다. 명령의 성공적인 구현 확인한 후 service cron stopexit종료 시간 초과 작업을.

둘째, 일반 우편을 달성하기 위해

다음 단계는 작업이 메일을 시간 초과로 파일을 작성하는 것입니다. 에서 .env메일을 구성하는 데 필요한 파일에 대한 정보를 제공합니다.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=465
MAIL_USERNAME=244500972@qq.com
MAIL_PASSWORD=***** //填自己的邮箱密码
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=244500972@qq.com
MAIL_FROM_NAME=huangdj

1, 개방형 web.php, 추가 노선

$this->any('mail', 'HomeController@mail');//发邮件

2, Home다음 코드 컨트롤러를 추가 :

public function mail()
{
   //第一种方法
   \Mail::raw('定时发送邮件 测试', function ($message) {
       $message->from('[email protected]', '长乐未央');
       $message->subject('邮件主题 测试');
       $message->to('[email protected]');
   });

  //第二种方法
// \Mail::send('admin.mail', ['name' => 'holy'], function ($message) {
//     $message->to('[email protected]');
// });
}

테스트 : 터미널 인쇄 라우팅, 주소, 라우팅 방문하는 브라우저를 얻을 http://你的二级域名/admin/mail사서함 메시지를받을 수 있는지 여부를 확인 할 수 있습니다. 메시지의 성공적인 수신하면, 아래로 계속합니다. .

3, 작업 클래스 열 SendEmail.php수정 파일을 handle다음과 같이 방법 :

public function handle()
{
//写入文件
// file_put_contents("/var/www/crontab/file.txt", date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);

 \Mail::raw('定时发送邮件 测试', function ($message) {
    //查出要发邮件的所有用户的邮箱
    $customers = Customer::where('email', '<>', null)->get();
    foreach ($customers as $customer) {
         $message->from('[email protected]', 'huangdj');
         $message->subject('邮件主题 测试');

          //执行发送
         $message->bcc($customer->email);
      }
    });
}

마지막으로, 서버에 현재 프로젝트는, 타이머 명령을 시작 service cron restart, 메일 메시지를 수신하고 매 분마다 한 번 실행하면 볼 수있는 분을 기다립니다.

셋째, 증가 레디 스 큐

우리는 전자 우편의 많은 양의를 보낼 때, 우리는 백 엔드가 긴 작업을 완료 그래서, 메시지가 저장된 모든 큐에 전송 큐를 사용합니다. 정보의 많은 온라인 데이터베이스 큐를 사용하고, 여기에 내가 사용 redis큐를.

1, .env의 파일이 수정 QUEUE_DRIVER=sync입니다 QUEUE_DRIVER=redis
: 터미널 명령을 실행, 2 출시 대기열을 redis-server당신은 발견 할 것이다 predis명령을 실행가 설치되지 않은 확장 된 : composer require predis/predis설치합니다. 설치가 완료되면, 레디 스를 다시 시작합니다.
3, 작업 범주를 만들 : php artisan make:job SendReminderEmail성공적으로 실행이됩니다 후 app/Jobs디렉토리를 생성 SendReminderEmail.php다음과 같이 우리가 그 내용을 수정합니다

<?php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

use App\Customer;
use Illuminate\Contracts\Mail\Mailer;
class SendReminderEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $customer;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(Mailer $mailer)
    {
        $customer = $this->customer;

        $mailer->send('emails.reminder',['customer'=>$customer],function($message) use ($customer){
            $message->to($customer->email)->subject('新功能发布');
        });
    }
}

4 메일 부분도를 만들resources/views/emails/reminder.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        亲爱的{{$customer->nickname}},您好,长乐教育新发布了Laravel5.6使用redis实现群发邮件功能,立即去体验下吧:
        <a href="https://www.whphp.com/">前往长乐教育</a>
    </div>
</body>
</html>

넷째, 큐 작업을 밀어 - 수동 배포 작업을

1, web.php다음과 같은 경로를 추가 :

Route::get('mail/sendReminderEmail/{id}','MailController@sendReminderEmail');

2 컨트롤러를 만들 : php artisan make:controller MailController다음 코드 컨트롤러 쓰기 :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Customer;
use Mail;
use Storage;
use App\Jobs\SendReminderEmail;
class MailController extends Controller
{
    //发送提醒邮件
    public function sendReminderEmail(Request $request, $id)
    {
        $customer = Customer::findOrFail($id);

        $this->dispatch(new SendReminderEmail($customer));
    }
}

3, 큐 리스너를 실행합니다. 브라우저에서 액세스 http://你的二级域名/mail/sendReminderEmail/63하고 작업에 밀어 Redis큐. 명령 행에서 다음 명령을 실행하여 php artisan queue:work사서함 알림 전자 메일을 받게됩니다 참조로 이동합니다 다음과 :

4 지정된 큐 푸시 태스크는 수정 App\Console\Commands\SendEmail내부 handle메소드 코드는 다음과 같다 :

public function handle()
{
  \Mail::queue('定时发送邮件 测试', function ($message) {
      //查出要发邮件的所有用户的邮箱
      $customers = Customer::where('email', '<>', null)->get();
      foreach ($customers as $customer) {
           $message->from('[email protected]', 'huangdj');
           $message->subject('邮件主题 测试');

         //执行发送
		//$message->bcc($customer->email);

		//将任务推送到指定队列并延迟一分钟执行
        dispatch(new \App\Jobs\SendReminderEmail($customer->email))->onQueue('emails')->delay(60);
      }
  });
}

궁극적 인 시험 : 메일 전자 메일마다 분 수신 여부를 확인하려면
시작 : redis-server
시작 : php artisan queue:work
시작 정기 구현 :service cron restart

참고 :http://laravelacademy.org/post/2012.html
http://laravelacademy.org/post/222.html#ipt_kb_toc_222_14

잘 했어 !!!

게시 14 개 원래 기사 · 원 찬양 1 · 조회수 89

추천

출처blog.csdn.net/huangdj321/article/details/104929571