Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch an artisan command from a queued Job then delete the Job after execution using database driver

I'm using database driver to queue my jobs. I need to call an artisan command from a queued Job and when the Job has finished I need to remove it from the queue. This is my controller's code where I add the job in the queue

dispatch((new SendNewsletter())->onQueue('newsletter'));

This is my queued Job

<?php

namespace App\Jobs;

use App\Console\Commands\Newsletter;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SendNewsletter implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        app()->make(Newsletter::class)->handle();
    }
}

The artisan command I need to call is App\Console\Commands\Newsletter

and when the Job ends, this should remove it from the queue. This is AppServiceProvider class

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot() {
    Queue::after(function ($event) {
        if ($event->job->queue == 'newsletter') {
            $event->job->delete();
        }
    });
}

The Job is added correctly to the database queue and when I run php artisan queue:work the job is called multiple times endless. seems that Queue::after's callback is never called. any idea what am I missing ?

like image 371
simonecosci Avatar asked Sep 03 '25 15:09

simonecosci


1 Answers

Probably your job fails and it is added to queue trying to finsh the work correctly. Try calling the command in your job like this

\Artisan::call('your:command');

Instead of:

app()->make(Newsletter::class)->handle();

Where "your:command" is the command name, that you gave in the command class:

protected $signature = 'email:send {user}';
like image 97
Виктор Митков Avatar answered Sep 05 '25 05:09

Виктор Митков