How to schedule commands in laravel 5.1

 

 

let’s create a console command, which will be executed very often:

$ php artisan make:consoleManageWaitinglist

This will create a command that can be executed from the Artisan command-line tool. If you have used Laravel 4, you may be familiar with this type of command. These commands are stored in the Console/Commands/ directory.

To let Laravel know about it, we will need to add it to app/Console/Kernel.php in the $commands array:

protected $commands = [
    'MyCompany\Console\Commands\Inspire',
    'MyCompany\Console\Commands\ManageWaitinglist',
    ];

The contents will look like this:

<?php namespace MyCompany\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class ManageWaitinglist extends Command {

    /**
    * The console command name.
    *
    * @var string
    */
    protected $name = 'command:name';

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

    /**
    * Create a new command instance.
    *
    * @return void
    */
    public function __construct()
    {
        parent::__construct();
    }

    /**
    * Execute the console command.
    *
    * @return mixed
    */
    public function fire()
    {
        //
    }

    /**
    * Get the console command arguments.
    *
    * @return array
    */
    protected function getArguments()
    {
        return [
          ['example', InputArgument::REQUIRED, 'An example argument.'],
        ];
    }

    /**
    * Get the console command options.
    *
    * @return array
    */
    protected function getOptions()
    {
        return [
          ['example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null],
        ];
    }
}

The $name attribute is what will be called from Artisan. For example, if we set the following:

protected $name = 'manage:waitinglist';

Then, by running the following command, we can manage the waiting list:

$ php artisan manage:waitinglist

The getArguments() and getOptions() methods are similar methods with the same signature, but have different uses.

The getArguments() method specifies an array of arguments that must be used to launch the command. The getOptions() methods are specified with and can be optional, repeated, and with the VALUE_NONE option, they can be simply used as flags.

We will write the command’s main code inside the fire() method. If we want to dispatch a command from within this command, we’ll add the DispatchesCommands trait to the class as follows:

    use DispatchesCommands;
    
    <?php namespace MyCompany\Console\Commands;
    
    use Illuminate\Console\Command;
    use Illuminate\Foundation\Bus\DispatchesCommands;
    use Symfony\Component\Console\Input\InputOption;
    use Symfony\Component\Console\Input\InputArgument;
    
    class ManageWaitinglist extends Command {
    
        use DispatchesCommands;
        
        /**
        * The console command name.
        * @var string
         */
        protected $name = 'manage:waitinglist';
        
        /**
        * The console command description.
        * @var string
        */
        protected $description = 'Manage the accommodation waiting list.';

        /**
        * Create a new command instance.
        *
        * @return void
        */
        public function __construct()
        {
            parent::__construct();
        }

        /**
        * Execute the console command.
        * @return mixed
        */
        public function fire()
        {
            // TODO: write business logic to manage waiting list
            if ($roomIsAvailableFor($user)) {
                $this->dispatch(new ReserveRoomCommand());
            }
        }

        /**
        * Get the console command arguments.
        * @return array
        */
        protected function getArguments()
        {
            return [];
        }

        /**
        * Get the console command options.
        * @return array
        */
        protected function getOptions()
        {
            return [];
        }
}

The command scheduler

Now, we will schedule this command to run every 10 minutes. Traditionally, this was done by creating a cron job to execute the Laravel console’s command. Now, Laravel 5 provides a new mechanism to do this—the command scheduler.

The new artisan command is run as follows:

$ php artisan schedule:run

By simply adding this command to the cron, Laravel will automatically run all of the commands that are in the Kernel.php file.

The commands need to be added to the Schedule function as follows:

protected function schedule(Schedule $schedule)
    {
        $schedule->command('inspire')
             ->hourly();
        $schedule->command('manage:waitinglist')
            ->everyFiveMinutes();

    }

The inspire command is a sample command provided by Laravel to demonstrate the functionality. We will simply add our command. This will call the manage:waitinglist command every 5 minutes—it couldn’t be much easier than that.

Now we need to modify the crontab file to have Artisan run the scheduler.

The crontab is a file that contains commands to be run at certain times. To modify this file, type the following command:

$ sudo crontab -e

We will use vi or whichever the assigned editor is to modify the cron table. Adding the following line will tell cron to run the scheduler every minute:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares