This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Laravel Cron Jobs Scheduling To Make Automation Easier

Updated on June 16, 2021

7 Min Read
Laravel Cron Jobs

When working on live systems, often there is a need of executing a periodic task on the server like sending emails, database cleanup, and generating reports. To automate these tasks I use Laravel Cron Job 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 specific dates 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. Moreover, the simplicity brought by Laravel Cron Job Scheduling is even more pronounced when you harness the capabilities of optimized Laravel hosting.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

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 a 1-Click installation of the Laravel application. You can sign up at Cloudways – it is 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 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.

laravel banner cta

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 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('[email protected]');

       $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 are 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 an 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.

With Cloudways’ Laravel Hosting: Unleash Full Potential of Your Laravel Projects

Experience unmatched speed, security, and scalability for your web applications. Elevate your Laravel Hosting journey today!

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 the Laravel Cron job scheduler.

I hope you like the article. If you have any queries, please do feel free to comment below.

Q) How do I schedule a cron job in Laravel?Here’s how you can schedule a cron job in Laravel:

  • Open your terminal and navigate to your Laravel project’s root directory.
  • Edit the crontab file by running the command crontab -e.
  • Add a new line to the crontab file with the following format:
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
  • Save the changes to the crontab file
  • In your Laravel project, open the app/Console/Kernel.php file.
  • Within the schedule method, you can define your scheduled tasks using the scheduler’s fluent API
protected function schedule(Schedule $schedule)
{
    $schedule->command('my:command')->everyMinute();
}
  • Save the changes to the Kernel.php file.

Now, the cron job is scheduled to run every minute, You can customize the scheduling frequency and add more scheduled tasks according to your requirements for example everyMinute, daily, weekly, cron, etc.

Q) What is the purpose of cron jobs in Laravel?

A) The purpose of cron jobs in Laravel is to automate and schedule recurring tasks or jobs within the application, such as database cleanup, sending periodic notifications, running scheduled commands, or performing any other predefined operations at specific intervals.

Q) Can I schedule multiple cron jobs in Laravel?

A) Yes, you can schedule multiple cron jobs in Laravel by defining multiple scheduled tasks using the Laravel scheduler’s fluent API in the app/Console/Kernel.php file, each with their own frequency and commands or closures to be executed.

Share your opinion in the comment section. COMMENT NOW

Share This Article

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.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now