Javier Núñez Fernández Full Stack Web Engineer

Managing cron jobs with Laravel 5

TASK JOBS WITH CRONTAB

If we want to schedule tasks (on a UNIX based system) that will be executing every so often, we need to edit the crontab.

Crontab is a file that contains a list of scripts that we want to be run periodically. For example, if we want to run a users_cleanup script that deletes all users that have being removed everyday at 20:00h, we should edit the CRONTAB and insert a line like this:

Crontab format

TASK JOBS WITH LARAVEL 5

Never again! Laravel 5 helps us not to have to use this file and provides a Task Scheduler that can create clear and intuitive job tasks.

1. SCHEDULE ARTISAN COMMAND EACH MINUTE

First you have to include a single line in CRONTAB, that will execute the Laravel Scheduler. To edit CRONTAB we have to execute from the shell:


$ crontab -e

And then add this line:


* * * * * /usr/local/bin/php /var/www/example.com/artisan schedule:run 1>> /dev/null 2>&1

The PHP command in Ubuntu used to be in /usr/local/bin/php, but it can be located wherever you want. The "* * * * *" means that the script will execute every minute. Then Laravel Scheduler will execute the tasks it have.

2. DEFINE YOUR SCHEDULE TASKS IN KERNEL.PHP

You should define your task jobs inside Schedule method on app/Console/Kernel.php file. If we want to schedule a job like the one we created for CRONTAB example, we should add the following lines to that method:



namespace App\Console;

use DB;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        'App\Console\Commands\Inspire',
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            DB::table('users')->deleteInactive();
        })->dailyAt('20:00');
    }
}

As you can see, we are scheduling the task with a comprehensive command:



$schedule->call(function () {
    DB::table('users')->deleteInactive();
})->dailyAt('20:00');

And that's all, we have our task scheduled!