Dispatch Laravel jobs via Artisan

Overview

Dispatch Laravel jobs via Artisan

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This package can register jobs as Artisan commands. All you need to do is let your job implement the empty ArtisanDispatchable interface.

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable;

class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
{
    public function handle()
    {
        // perform some work...
    }
}

This allows the job to be executed via Artisan.

php artisan process-podcast

Why we created this package

Laravel's scheduler will perform all tasks sequentially. When you add a scheduled task to the scheduler, the task should perform its work as fast as possible, so no other tasks will have to wait.

If you have a task that needs to run every minute and its runtime is close to a minute, you should not use a simple Artisan command, as this will result in the delay of all other minute-ly tasks.

Long-running tasks should be performed by jobs that perform their work on the queue. Laravel has the ability to schedule queued jobs. This way, those tasks will not block the scheduler.

$schedule->job(new ProcessPodcast)->everyFiveMinutes();

The downside of this approach is that you cannot run that job via Artisan anymore. You have to choose between using an artisan command + blocking the scheduler on the one hand, and job + not blocking the scheduler on the other hand.

Using our package, you don't have to make that choice anymore. When letting your job implement Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable, you will not block the scheduler and can still execute the logic via Artisan.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-artisan-dispatchable

You can publish and run the migrations with:

Optionally, uou can publish the config file with:

php artisan vendor:publish --provider="Spatie\ArtisanDispatchable\ArtisanDispatchableServiceProvider" --tag="artisan-dispatchable-config"

This is the contents of the published config file:

return [
    /*
     * These directories will be scanned for dispatchable jobs. They
     * will be registered automatically to Artisan.
     */
    'auto_discover_dispatchable_jobs' => [
        app()->path(),
    ],

    /*
     * This directory will be used as the base path when scanning
     * for dispatchable jobs.
     */
    'auto_discover_base_path' => base_path(),

    /*
     * In production, you likely don't want the package to auto-discover dispatchable
     * jobs every time Artisan is invoked. The package can cache discovered job.
     *
     * Here you can specify where the cache should be stored.
     */
    'cache_file' => storage_path('app/artisan-dispatchable/artisan-dispatchable-jobs.php'),
];

Usage

All you need to do is let your job implement the empty ArtisanDispatchable interface.

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable;

class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
{
    public function handle()
    {
        // perform some work...
    }
}

This allows the job to be executed via Artisan.

php artisan process-podcast

This job will not be queued, but will be immediately executed inside the executed artisan command.

Queueing jobs via Artisan

If you want to put your job on the queue instead of executing it immediately, add the queued option.

php artisan process-podcast --queued

Passing arguments to a job

If your job has constructor arguments, you may pass those arguments via options on the artisan command.

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable;


class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
{
    public function __construct(
        string $myFirstArgument, 
    ) {}

    public function handle()
    {
        // perform some work...
    }
}

Via artisan, you can call the job like this

php artisan process-podcast --my-first-argument="My string value"

Using Eloquent models as arguments

If your job argument is an eloquent model, you may pass the id of the model to the artisan command option.

use App\Models\Podcast;
use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable;

class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
{
    public function __construct(
        Podcast $podcast, 
    ) {}

    public function handle()
    {
        // perform some work...
    }
}

Here's how you can execute this job with podcast id 1234

php artisan process-podcast --podcast="1234"

Customizing the name of the command

By default, the artisan command name of a job, is the base name of job in kebab-case.

You can set a custom name by setting a property named artisanName on your job.

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable;

class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
{
     public string $artisanName = 'my-app:process-my-podcast';

    public function handle()
    {
        // perform some work...
    }
}

This job can now be executed with this command:

php artisan my-app:process-my-podcast

Customizing the description of the command

To add a description to the lists of artisan command, add a property $artisanDescription to your job.

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\ArtisanDispatchable\Jobs\ArtisanDispatchable;

class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
{
     public string $artisanDescription = 'This a custom description';

    public function handle()
    {
        // perform some work...
    }
}

Caching discovered jobs

This package can automatically discover jobs that implement ArtisanDispatchable and what their artisan command should be through looping through all classes and performing some reflection. In a local environment this is perfect, as the performance hit is not too bad, and you don't have to do anything special besides letting your job implement ArtisanDispatchable.

In a production environment, you probably don't want to loop through all classes on every request. The package contains a command to cache all discovered jobs.

php artisan artisan-dispatchable:cache-artisan-dispatchable-jobs

You probably want to call that command during your deployment of your app. This will create cache file at the location specified in the cache_file key of the artisan-dispatchable config file.

Should you want to clear the cache, you can execute this command:

php artisan artisan-dispatchable:clear-artisan-dispatchable-jobs

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Create Laravel views (blade template) using 'php artisan' command-line interface
Create Laravel views (blade template) using 'php artisan' command-line interface

About LaraBit Have you ever wonder to create Laravel views (Blade Templates) using the same type of artisan commands that you usually use to create ne

Generate services in Laravel with the artisan command
Generate services in Laravel with the artisan command

Laravel Service Generator Quickly generate services for your projects! Table of Contents Features Installation Usage Generate services Generate servic

A Laravel Artisan SQL Interactive Interface
A Laravel Artisan SQL Interactive Interface

sqli A Laravel 4 & 5 Artisan SQL Interactive Interface, plus a handful of Artisan commands to execute SQL queries. sqli It's like tinker for SQL, just

An artisan command for using multiple environment configurations in Laravel 5

Laravel 5 env An artisan command for managing multiple .env of your Laravel 5 app. Installation Copy EnvCommand.php to app/Console/Commands/ of your L

Package for Laravel that gives artisan commands to setup and edit environment files.
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

This package is to add a web interface for Laravel 5 and earlier Artisan.
This package is to add a web interface for Laravel 5 and earlier Artisan.

Nice Artisan This package is to add a web interface for Laravel 5 and earlier Artisan. Installation Add Nice Artisan to your composer.json file : For

A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers.

Artisan UI A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers. Supported commands must be

A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands.

artisan.page A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands. Generation The generation of the manifest files is d

Laravel API architecture builder based on artisan commands.

πŸ§‘β€πŸ”¬ API-Formula Laravel API architecture builder based on artisan commands. This package provides a nice and fluent way to generate combined control

Comments
  • accept arguments with no type

    accept arguments with no type

    This PR takes care of arguments without types. E.g.

    class ProcessPodcast implements ShouldQueue, ArtisanDispatchable
    {
        public function __construct($podcast) {
             ...
        }
    }
    
    opened by pkboom 2
  • Allow users to specify a custom command name prefix

    Allow users to specify a custom command name prefix

    This allows a user to specify a custom command prefix, such as 'job', making the generated commands distinct from the "normal" commands plus also allowing one to list those commands via for example:

    php artisan list job
    

    This command would list all commands under the job namespace giving an overview what commands / jobs are available

    opened by abenerd 1
  • Review Seb

    Review Seb

    Some additional remarks:

    • ArtisanJobsRepository::registerAll and ArtisanDispatchableServiceProvider::packageBooted contain duplicate code
    • Clean up ray() calls
    • Suggestion: ProcessPodcast job as an example like in the Laravel docs
    opened by sebastiandedeyne 0
Releases(1.3.0)
Owner
Spatie
We create products and courses for the developer community
Spatie
πŸ“ Artisan Menu - Use Artisan via an elegant console GUI

?? Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

Jordan Hall 148 Nov 29, 2022
Execute Laravel Artisan commands via REST APIs and HTTP requests safely.

Artisan Api There might be some times you wanted to execute an Artisan command, but you did not have access to shell or SSH. Here we brought REST API

Alireza 11 Sep 7, 2022
Add variables to the payload of all jobs in a Laravel app

Inject extra info to the payloads of all jobs in a Laravel app This package makes it easy to inject things in every job. Imagine that you want to have

Spatie 62 Dec 9, 2022
This package allows you to easily track your laravel jobs!

Trackable Jobs For Laravel This package allows you to track your laravel jobs! Using this package, you can easily persist the output and the status of

Mateus Junges 220 Dec 25, 2022
Chain Laravel jobs without having to glue it to a starting job

Laravel Job Chainer JobChainer does chain a variable amount of jobs by adding them with the add() method. This makes it possible to chain jobs without

Just Iversen 69 Nov 18, 2022
A Laravel package to monitor the status and history of jobs on the queue.

Monitored Jobs for Laravel Overview This package tracks the status and history of your queued jobs by hooking into the events that Laravel fires for i

Aryeo 9 Dec 9, 2022
This project is based on the aggregation of jobs from some technology companies.

FIND-JOBS-ALERT ?? ?? ?? This project is based on the aggregation of jobs from some technology companies. Check below, some companies avaliable in pro

Wellisson Ribeiro 2 Dec 1, 2021
A site which you can apply jobs or search for employees with cool functionalities..

About App An App which you can apply jobs or search for employees with cool functionalities. Some Pics of App Click Image to Zoom in Sign In & Up Empl

Fatih Canbolat 1 Jan 7, 2022
πŸ‘€ Manage your views in Laravel projects through artisan

Artisan View This package adds a handful of view-related commands to Artisan in your Laravel project. Generate blade files that extend other views, sc

Sven Luijten 842 Dec 29, 2022
πŸ“¦ Adds Laravel Packages Support to Lumen and Vendor Publish Artisan Command.

Laravel Package Support for Lumen: Makes Lumen compatible with Laravel Packages. You can use any Laravel Packages in Lumen by installing Larasupport Package.

Irfaq Syed 127 Dec 17, 2022