How to Schedule Cron in Laravel to Automate Tasks

Cron jobs are useful to automatically execute scheduled tasks. To run these jobs, you need to add a cron entry per task. But, it can become harder to manage if you are running multiple tasks. To add or remove the cron entry, every time you need to SSH into the server.

Laravel resolves the problem of managing multiple cron entries. Laravel allows you to add all scheduled tasks in one place. Then by running a single command on a server all your tasks start executing as per the given schedules. In this article, we study how to schedule a cron in Laravel to automate our tasks.

Why Do We Need to Run Cron?

There are several examples where we need to run a cron job. You may be running an online store and you want to send promotional offers to your customers. Or you have a membership website and you wish to send the reminder email to users about their renewal subscription plan. To accomplish this work, we write a program for this task and set a cron for it. Your server will look for the time set with a cron and execute the script automatically. You don’t need to look at the clock and run the program manually.

Schedule A Cron in Laravel

For our article, let’s take a real-world example. I assume we have a bunch of users in the Laravel database. Every midnight we should send an email to all users informing them about the new promotional offer. By doing this, our users will come to know about new offers and our sales can get more attention.

You should have stored all your user’s information in the users table. I will get the user’s emails from this table and send them an email. I’ll write a code in such a way that it’ll run every day at midnight.

Open the app/Console/Kernel.php file. Add the User model and Mail facade to the file as shown below.

<?php
 
namespace App\Console;
 
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Models\User; // User model
use Mail; // Mail Facade
 
class Kernel extends ConsoleKernel
{
    ....
}

This Kernel class has a schedule() method where we have to write one or multiple tasks which require to automate. In our case, as we need to send an email to users I write the code as follows.

<?php
 
namespace App\Console;
 
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\User;
use Mail;
 
class Kernel extends ConsoleKernel
{
    ....
 
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            $arr_users = User::all();
 
            if(count($arr_users) > 0) {
                foreach ($arr_users as $user) {
                    $name = $user->name;
                    $email = $user->email;
                    $data = array("name" => $name, "body" => "This is our new promotional offer");
                    Mail::send('emails.mail', $data, function($message) use ($name, $email) {
                        $message->to($email, $name)
                                ->subject('New Offer Launched');
                        $message->from('admin@artisansweb.net', 'Artisans Web');
                    });
                }
            }
        })->daily();
 
        // you can add more schedules here
    }
    ....
}

In the code above, we are sending emails to users with the help of Mail facade. Here we need to create a mail.blade file under the resources/views/emails directory.

mail.blade.php

Hi <strong>{{ $name }}</strong>,
 
<p>{{ $body }}</p>

As our goal is to send an email at midnight I used the daily() method. Laravel provides different schedule frequency options which you’ll find in the documentation.

Before setting a cron on production, you may want to test it locally. For testing, change the schedule frequency to the everyMinute() instead of daily(). After that, run the below Artisan command:

php artisan schedule:work

This command will invoke the scheduler every minute and perform the given task.

Add Cron Entry to Your Server

Once you are tested the Laravel scheduler, set this schedular on the production by adding the below cron entry on your server.

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

Make sure you have set the path of your project correctly. This Cron will call the Laravel scheduler every minute. It automatically runs the schedule:run command and execute your scheduled tasks.

I hope you may have learned how to schedule a cron in Laravel to automate your tasks. It should help you to get the benefit of the Laravel Scheduling feature.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published.