X
    Categories: Learn Laravel Tutorials, Tips And Guides

Laravel Cron Jobs Scheduling To Make Automation Easier

When working on live systems, often there is a need of executing a periodic task on the server like for sending emails, database cleanup and generating reports. To automate these tasks I use Laravel cron jobs scheduling.

Cron is the task scheduler mechanism of Unix/linux operating systems. Cron schedules tasks based on a pre-specified time period like numbers of days, weeks, months, or even a specific date and time. To achieve this, cron uses the specific configuration file called ‘crontab’, also known as ‘Cron Table’, to manage the scheduling process. Cron jobs are composed of two parts, the cron expression, and a shell command that needs to be run. Cron expression is used for setting the schedule frequency.

* * * * * command/to/run

However, this is just the basic theory of Cron. To understand more about how to create Cron jobs and how they actually work, you should read the Cron Jobs article. However, Laravel Cron Job Scheduling makes the entire process very easy.

Laravel Cron Job Scheduling

Laravel provides an easy way for task scheduling. Laravel’s ‘Command Scheduler’ allows you to easily define the schedule of the commands within Laravel itself. When using the scheduler, only one Cron entry is needed on the server. Your task schedule is defined in the app/Console/Kernel.php file’s schedule method.

Now let’s undertake the command scheduling with a simple example. I will create a custom artisan command which will send an email to all the users. Let’s assume the email contains a report which needs to be sent to the users every hour.

Installing Laravel Application

For the purpose of this tutorial, I will use the Cloudways Platform because it provides 1-Click installation of the Laravel application. You can sign up at Cloudways – its free!

Login to your Cloudways accounts and create a new server. Fill in the server and the application details and select Laravel as your application. That’s it.

Create Custom Artisan Command

Now that you’re setup on Cloudways, go to to your server tab, launch SSH terminal and connect the terminal with your server by using the given credentials in your server tab.

Now type the following commands:

cd applications
cd your_app_name/public_html

You should now be in the root folder of your application. Type the following command to create the custom artisan command:

php artisan make:command HourlyUpdate

This command will create a new command class in the app/Console/Commands directory. Head to this command file and you will find the following code in it:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class HourlyUpdate extends Command

{

   /**

    * The name and signature of the console command.

    *

    * @var string

    */

   protected $signature = '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 handle()

   {

       //

   }

}

In this code locate:

protected $signature = 'command:name';

Whatever you replace the words command:name with, will be used to execute the full command. For demonstration purposes, I will alter this command to read:

protected $signature = 'hour:update';

Now locate:

protected $description = ‘Command description’;

This is where you have to place the description of what this command will actually achieve. When the Artisan list executes, this command will be listed alongside the custom description you insert with the command. For my purpose, I am going to change the generic description command to:

protected $description = ‘Send an hourly email to all the users’;

Finally, you now want to locate the handle() function that is called whenever you execute this command. This is where the logic or the code of your command should be present.

In this example, I need to send an email to all the users. To understand how the email functionality works on Laravel, I would suggest you to read my previous article on sending emails in Laravel. Place the following code in the handle() function:

public function handle()

   {

       $user = User::all();

       foreach ($user as $a)

       {



   Mail::raw("This is automatically generated Hourly Update", function($message) use ($a)

   {

       $message->from('saquib.gt@gmail.com');

       $message->to($a->email)->subject('Hourly Update');

   });

   }



   $this->info('Hourly Update has been send successfully');

   }

This should fetch all the users from the user table and send them emails. Now that the command is created, you will need to register it.

For registering the command, go to app/console/kernal.php  and place the following code:

<?php

namespace App\Console;

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 = [

       Commands\HourlyUpdate::class

   ];



   /**

    * Define the application's command schedule.

    *

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

    * @return void

    */

   protected function schedule(Schedule $schedule)

   {

       $schedule->command('hour:update')

                ->hourly();

   }



   /**

    * Register the Closure based commands for the application.

    *

    * @return void

    */

   protected function commands()

   {

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

   }

}

In this file, protected $commands is where you have to register the command class and schedule function is where you set the command to be executed at the specified time interval. This is where the cron jobs are handled.

Now let’s run the command in the terminal. Go to the root of your project and run the following command:

php artisan list

You will see your custom command in the list. Now execute the command itself:

As you can see I ran the command with the name I placed in the protected $signature = ‘command:name’; Now since the command is successfully executed, let’s take a look at the scheduler.

Scheduling Artisan Commands

The scheduler executes the commands (in this case only) on an hourly basis. To make it happen, I will set the schedule function in the kernal.php file that I discussed earlier in the article. Now locate the following code in the file:

 protected function schedule(Schedule $schedule)

   {
       $schedule->command('hour:update')

                ->hourly();
   }

$schedule->command(‘hour:update’) is where you have set which command needs to be executed and  ->hourly(); defines the time interval. In this example, I have set the time interval on hourly basis but there are many more frequencies that can be set as provided in the official Laravel documentation To set a different time period, all you will need to do is replace this ->hourly(); with an option from the following list:

Method Description
->cron(‘* * * * * *’); Run the task on a custom Cron schedule
->everyMinute(); Run the task every minute
->everyFiveMinutes(); Run the task every five minutes
->everyTenMinutes(); Run the task every ten minutes
->everyThirtyMinutes(); Run the task every thirty minutes
->hourly(); Run the task every hour
->hourlyAt(17); Run the task every hour at 17 mins past the hour
->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
->weekly(); Run the task every week
->monthly(); Run the task every month
->monthlyOn(4, ’15:00′); Run the task every month on the 4th at 15:00
->quarterly(); Run the task every quarter
->yearly(); Run the task every year
->timezone(‘America/New_York’); Set the timezone

Activate Laravel Cron Jobs Scheduler

Now to activate the scheduled jobs, run the cron command. Go to your application from the Applications tab, and then to the Cron Jobs Manager.

In the advance tab of Cloudways cron job manager, place the following command:

* * * * * php /home/master/applications/your_project_folder_name/public_html/artisan schedule:run >> /dev/null 2>&1

When done, make sure to save changes. That’s it! Laravel Cron Jobs will be executed and all your scheduled jobs will work accordingly.

Conclusion

In this article, I demonstrated two highly effective Laravel features. First I explained how you can create a custom Artisan command, and then I showed you how to automate the whole process in the given time interval by using Laravel cron job scheduler.

I hope you like the article if you feel any query feel free to comment below.

Saquib Rizwan: Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends. You can email him at saquib.rizwan@cloudways.com