Back to Blog 7 min read

Laravel Scheduler And Cron Job

In Laravel, the Scheduler is a component that allows you to define and schedule recurring commands or tasks to run automatically. You can use the Sch...

In Laravel, the Scheduler is a component that allows you to define and schedule recurring commands or tasks to run automatically. You can use the Scheduler to schedule a wide variety of tasks, such as sending emails, cleaning up old data, or checking for new data.

Scheduler helps to offload the tasks and with that it makes performance better. If we use Laravel scheduler then we don't need to set manual cron jobs, such as defining multiple urls with different time. And lot of things like that.

Additionally, Laravel scheduler insure that tasks are running consistently and in case we are dependent on those tasks then it's very useful. For example: We can use scheduler to schedule emails and send them using under the hood functionality of Job and Queue.

Path To Scheduler File

To use the Scheduler in Laravel, We will need to define scheduled tasks in the app/Console/Kernel.php file, and then use the php artisan schedule:run command to run the tasks.

The Scheduler will take care of running the tasks at the specified intervals, so you don't have to worry about setting up and managing cron jobs or other scheduling mechanisms.

Use Of Laravel Schedule

We use Laravel scheduler in various cases. One example that we have seen above that is, we can use it to send mails.

Scheduling Artisan Commands

But the most important thing is that we can schedule the artisan commands using scheduler. Let me show an example file of Laravel scheduler. For that we will go into directory Your Project \app\Console\Kernel.php.

<?php

namespace App\Console;

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

class Kernel extends ConsoleKernel
{
    /** 
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('queue:listen')->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}

As you can see in the above code picture that I have defined a artisan command into schedule function. And the artisan commands that we use in our command line interface. We can define them in schedule function easily. Also can set the time at the end without passing start or something. Just by a single line. (everyminute()).

Running Backups

In some case, If we want to take a copy of our data on regular basis then also we can use the laravel scheduler to run backups. Well, not a promotion but spatie also have a package on backups don't know the name exactly. But If we are working with some huge and some really important data. In case any big data of government then it can be useful to run backups.

Removing Unused Data and Cleaning Database

Unused data the data that is stored in database and we aren't using. Just in case, Years old data still there in database then we can run scheduled command for a particular time, after the specified time data should be removed or this action can be done with any table.

Laravel scheduler is the best feature and a developer would love this feature. Because now we don't need to specify cron jobs for each tasks. Just go to scheduler and schedule the commands and whatever action you want to apply.

See the below example from the documentation itself.

<?php

namespace App\Console;

use App\Jobs\JobMailNotification;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;

class Kernel extends ConsoleKernel
{
    /** 
     * 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();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}

Sending Reminders

Laravel scheduler allows you to define the time when you want to run that schedule. When schedule means running something on a particular time. Well, For example if you are running a ecommerce website using laravel then using laravel scheduler you can send gift,birthday messages, new year wishes and lot of things like to your regular customers or some other interesting and business reminders as well.

See the below example:


//these are the methods that you can use to define time in your laravel scheduler.

->cron('* * * * *');	Run the task on a custom cron schedule
->everyMinute();	Run the task every minute
->everyTwoMinutes();	Run the task every two minutes
->everyThreeMinutes();	Run the task every three minutes
->everyFourMinutes();	Run the task every four minutes
->everyFiveMinutes();	Run the task every five minutes
->everyTenMinutes();	Run the task every ten minutes
->everyFifteenMinutes();	Run the task every fifteen minutes
->everyThirtyMinutes();	Run the task every thirty minutes
->hourly();	Run the task every hour
->hourlyAt(17);	Run the task every hour at 17 minutes past the hour
->everyOddHour();	Run the task every odd hour
->everyTwoHours();	Run the task every two hours
->everyThreeHours();	Run the task every three hours
->everyFourHours();	Run the task every four hours
->everySixHours();	Run the task every six hours
->daily();	Run the task every day at midnight
->dailyAt('13:00');	Run the task every day at 13:00
->twiceDaily(1, 13);	Run the task daily at 1:00 & 13:00
->twiceDailyAt(1, 13, 15);	Run the task daily at 1:15 & 13:15
->weekly();	Run the task every Sunday at 00:00
->weeklyOn(1, '8:00');	Run the task every week on Monday at 8:00
->monthly();	Run the task on the first day of every month at 00:00
->monthlyOn(4, '15:00');	Run the task every month on the 4th at 15:00
->twiceMonthly(1, 16, '13:00');	Run the task monthly on the 1st and 16th at 13:00
->lastDayOfMonth('15:00');	Run the task on the last day of the month at 15:00
->quarterly();	Run the task on the first day of every quarter at 00:00
->quarterlyOn(4, '14:00');	Run the task every quarter on the 4th at 14:00
->yearly();	Run the task on the first day of every year at 00:00
->yearlyOn(6, 1, '17:00');	Run the task every year on June 1st at 17:00
->timezone('America/New_York');	Set the timezone for the task

Difference Between Cron Job and Laravel Scheduler

I won't make it too much difficult because both do the same thing. But Scheduler is much powerful and easy to handle thing for Laravel developers.

  1. When we define cron jobs then we need to define cron job in cron tab and developers should be familiar with cron syntax as well. But when we are using scheduler we dont' need to be familiar with cron syntax, We can just put the specific time in simple english laravel function : as you can see above.
  2. Laravel's Scheduler is a component that provides a convenient way to define and schedule recurring tasks within the Laravel application and on the other hand cron tasks are run as separate processes.

Conclusion

Overall, the Laravel Scheduler is a convenient and powerful tool for scheduling tasks within a Laravel application, and it can be a good alternative to cron for some use cases.

Schedule Emails In Laravel to Save Loading Time