Task Scheduling in Laravel

As we know Cron is a time based job scheduler. You have to create entry in cron jobs for each tasks we need to run. It becomes a difficulty because your task scheduler is no more in source control and you must SSH into your server to add additional Cron entries. Laravel has a command scheduler and it helps you to easily and expressively define your command schedule within Laravel itself. You need only a single cron entry on your server when using task scheduler. When starting the scheduler add the following Cron entry to your server.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

This entry will call the Laravel command scheduler every minute when schedule:run command is executed. Define your tasks in the schedule method of the App\Console\Kernel class.  For example we are defining a task called Closure to be executed every day at midnight.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;

use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

use Illuminate\Support\Facades\DB;

class Kernel extends ConsoleKernel

{

    /**

     * The Artisan commands provided by your application.

     *

     * @var array

     */

    protected $commands = [

//

];


    /**

     * Define the application's command schedule.

     *

     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule

     * @return void

     */

    protected function schedule(Schedule $schedule)

    {

        $schedule->call(function () {

            DB::table('recent_users')->delete();

        })->daily();

    }

}

You have to add an __invoke method .

$schedule->call(new DeleteRecentUsers)->daily();

Then use a command method to schedule artisan command.

$schedule->command('emails:send Taylor --force')->daily();

$schedule->command(EmailsCommand::class, ['Taylor','--force'])->daily();

The job method may be used to schedule a queued job, it gives a better way to schedule jobs without using a call method manually create Closure to queue  the job.

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

// Dispatch the job to the "heartbeats" queue...

$schedule->job(new Heartbeat, 'heartbeats')->everyFiveMinutes();

To issue a command to operating system use exec method.

$schedule->exec('node/home/forge/script.js')->daily();

There are methods to select frequency , timezone, to set time.