Džuris
Džuris

Reputation: 2234

How to execute a job from queue?

I am using Laravel Queue with the database driver to delay some tasks.

However, I can't run the designed worker because of reasons. lnstead I decided to use the scheduler to call my own worker every 5 minutes.

However, I can't really understand how to implement the worker and I can't fully get my head aroujd the original code myself. I would like to retrieve the jobs that are due from the database and run them. How to do that?

Is there some generic model for jobs that can load them correctly like DatabaseJob::whereDate(......)->get()?

Do I have to load something (payload?) for the jobs or will it happen automatically? Which methods do I need to execute the job? ´handle()´? ´fire()´? Or something else?

Upvotes: 1

Views: 6234

Answers (2)

Travis Britz
Travis Britz

Reputation: 5552

You can run artisan commands from your code by using the call() method on the Artisan facade. For example, this will process all ready jobs from the default queue and exit when it's done:

Artisan::call('queue:work', ['--stop-when-empty' => true])

From the docs:

Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The call method accepts either the command's name or class as the first argument, and an array of command parameters as the second argument. The exit code will be returned:

Route::get('/foo', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    // });

The same syntax would work for scheduling:

$schedule->command('queue:work', [...])->everyFiveMinutes();

As others have pointed out, running the worker inside schedule:run may lead to undesired behavior such as skipped scheduled tasks.

For your questions on how dispatching and running queued jobs works, this is the place to start: https://laravel.com/docs/5.7/queues

Upvotes: 2

vishnu sharma
vishnu sharma

Reputation: 72

You can setup horizon for queue job monitoring reference link:

https://laravel.com/docs/5.7/horizon

Or Run pre Artisan cmd

php artisan queue:listen database --queue=high

Upvotes: 1

Related Questions