What I've found myself usually doing when working with Queues in Laravel is a need to run jobs manually. Especially the jobs that have no arguments, usually some maintenance tasks like pruning excess logs generating a suggestions for user. These kind of jobs are a great candidates to be scheduled as they are more abstract and generally do not immediately affect the user experience. This is a contrast to jobs that do processing, for instance when a user uploads a photo, they would like it appear in the application as soon as possible, ideally without any delay. If the photo appears in the app 10 minutes later, the user might be long gone, never to return back.
Make a job
Job boilerplate can be generated using artisan:
php artisan make:job RefillFridge
Populate the RefillFridge
job class with required commands as needed. For
a very quick and dirty testing I sometimes just create a route closure like
this:
<?php
use App\Jobs\RefillFridge;
Route::get('refill', function () {
dispatch(new RefillFridge());
});
This is tempting, especially since it is super easy to just pres F5 to refresh the GET route in the browser to get the job dispatched. But routes obviously are not meant to be abused in this way.
Use Tinker
Another way to get the Job done without any additional code is to use Tinker.
php artisan tinker --ansi
>>> dispatch(new App\Jobs\RefillFridge)
=> Illuminate\Foundation\Bus\PendingDispatch {#3502}
This could be enough for many people, but still requires some writing to do. Tinker has a history that can be reverse-searched via CTRL-R, the same way as in Bash or zsh for instance, but it get's cleared sometimes, and I did not figure out when exactly it does it yet, so it is good to keep this in mind.
Making a command
Command boilerplate can be generated via artisan as well:
php artisan make:command RefillFridge
Now dispatch the RefillFridge
job from the RefillFridge
command. This a
little tricky. Since both classes are called the same, although under
different namespaces, we either need to provide absolute paths or an alias
via as
keyword. I prefer the alias method as it keeps repetition low and
makes it more obvious glancing at the top of the file what the class
interacts with. The minimal code is below:
<?php
namespace App\Console\Commands;
use App\Jobs\RefillFridge as RefillFridgeJob;
use Illuminate\Console\Command;
use Illuminate\Contracts\Bus\Dispatcher;
class GeneratePlan extends Command {
protected $signature = 'refill:fridge';
protected $description = 'Puts fresh food into the fridge';
public function handle() {
return app(Dispatcher::class)->dispatch(new RefillFridgeJob());
}
}
As opposed to previous methods, we also need an access to the app's
Dispatcher
in the commands. This will use the default queue and the
default connection. Run the command as usual:
php artisan refill:fridge
The queue worker should pick this up in a moments.