Laravel:如何限制重试排队通知

时间:2018-06-21 10:38:24

标签: laravel

从Laravel手册中,我了解到我可以使用命令行(在启动队列时)或在作业类本身上设置$tries属性来限制重试已排队作业的次数。 https://laravel.com/docs/5.6/queues#max-job-attempts-and-timeout

我想设置作业本身内的最大重试次数,而不使用命令行,但是该作业实际上是一个自Illuminate\Notifications\Notification继承的自定义类,而不是App\Job。在这种情况下,是否可以限制尝试次数?

我尝试在客户通知中设置$tries属性,但没有任何效果。我也正在使用自定义渠道,但是设置$tries也不起作用。

2 个答案:

答案 0 :(得分:3)

在您的通知文件中,添加InteractsWithQueue特征。正是这种特质使您可以更改尝试次数。

use Illuminate\Queue\InteractsWithQueue;

class MyNotification extends Notification implements ShouldQueue
{
    use Queueable, InteractsWithQueue;

    public $tries = 3;

答案 1 :(得分:1)

从Laravel 5.7+开始,您可以通过向可排队通知中添加$tries属性来轻松地限制最大尝试次数。

PR作者(laravel/framework GitHub PR 26493#)的用法示例:

<?php

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class TestNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public $tries = 3; // Max tries

    public $timeout = 15; // Timeout seconds

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }
}