How to manually run a laravel/lumen job using command line

Oscar David picture Oscar David · Apr 12, 2017 · Viewed 21.4k times · Source

I have created a Job file in the folder app/Jobs/MyJob.php and i would like to run it just once, if its possible using command line.

Something like:

> php MyJob:run

what command should I use to run a method in this file or the handle?

Answer

mixel picture mixel · Jun 26, 2018

UPDATE

I created mxl/laravel-job composer package providing Laravel command for dispatching jobs from command line:

$ composer require mxl/laravel-job
$ php artisan job:dispatch YourJob # for jobs in app/Jobs directory (App\Jobs namespace)
$ php artisan job:dispatch '\Path\To\YourJob' # dispatch job by its full class name
$ php artisan job:dispatchNow YourJob # dispatch immediately
$ php artisan job:dispatch YourJob John 1990-01-01 # dispatch with parameters

Package also provides a way to reduce boilerplate by using base Job class and has FromParameters interface that allows to implement command line parameters parsing and use job from PHP code and command line simultaneously.

Read more about its features at the package GitHub page.

OLD ANSWER

Run

php artisan make:command DispatchJob

to create special artisan command that runs jobs.

Open created DispatchJob.php file and define DispatchJob class like this:

class DispatchJob extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'job:dispatch {job}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Dispatch job';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $class = '\\App\\Jobs\\' . $this->argument('job');
        dispatch(new $class());
    }
}

Now you should start queue worker:

php artisan queue:work

and after that you can run jobs from command line:

php artisan job:dispatch YourJobNameHere