在Laravel调度程序中调度作业是否有好处?

时间:2019-09-25 15:00:27

标签: php laravel

在我的应用程序中,我想通知管理员用户有不到一个月的时间来重新声明其类型。基本上应该是每12个月一次,所以我做了一个Mailable来接受用户。

<?php

namespace App\Mail\Admin;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;

class DeclarationDueToExpire extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * The user instance passed to this Mailable
     *
     * @var User
     */
    public $user;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
            ->to("npiinvestors@newable.co.uk")
            ->subject('Declaration due to expire for investor ' . $this->user->full_name)
            ->markdown('emails.admin.declaration-due-to-expire');
    }
}

现在通常我只是将其作为控制台命令并将其放入调度程序中

public function handle()
{
    User::whereDate('declaration_date', Carbon::today()->subMonths(11))->get()
        ->each(function ($user) {
            Mail::send(new DeclarationDueToExpire($user));
        });
}

我最近遇到过Jobs,所以我用Job编写了一个测试。

<?php

namespace Tests\Feature;

use App\Jobs\SendDeclarationDueToExpireEmail;
use App\Mail\Admin\DeclarationDueToExpire;
use App\User;
use Carbon\Carbon;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;

class DeclarationSoonToExpireTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function a_notification_is_sent_exactly_eleven_months_after_initial_declaration()
    {
        Mail::fake();

        $dueToExpire = factory(User::class)->create([
            'declaration_date' => Carbon::today()->subMonths(11)
        ]);

        dispatch(new SendDeclarationDueToExpireEmail);

        Mail::assertSent(DeclarationDueToExpire::class);
    }
}

由于我仍需要每天从调度程序中分派作业,因此在此情况下使用作业有什么好处吗?

此外,您会为每项可能长时间运行的任务工作吗?

最后,当通知可以发送可邮寄邮件时,你们如何区分MailablesNotifications

0 个答案:

没有答案