简体   繁体   中英

Laravel: How to limit retries on queued notifications

From the Laravel manual, I understand that I can limit the number of times a queued job is retried using either the command line (when starting the queue), or by setting the $tries property on the job class itself. https://laravel.com/docs/5.6/queues#max-job-attempts-and-timeout

I want to set the maximum number of retries within the job itself, not using the command line, however the job is actually a custom class that inherits from Illuminate\\Notifications\\Notification , not an App\\Job . In this case, is it possible to limit the number of tries?

I tried setting the $tries property in my customer notification, but it had no effect. I am using a custom channel as well, but setting the $tries there had no effect either.

In your notification file add the Queueable trait. It's this trait that gives you the possibility to alter the number of tries.

use Illuminate\Bus\Queueable;

class MyNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public $tries = 3;

As of Laravel 5.7+, you can easily limit maximum tries by adding $tries property to the Queueable Notification.

Usage example from the PR author ( 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!');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM