Web Application

How to Setup Cron Job Scheduling in Laravel – Tutorial

In any web application, we need specific administrative tasks that run periodically and doing that manually is not a good idea. Whether you want to send out emails to your customers on particular events or clean up the database tables at the specific time, you will need a task scheduling mechanism to take care of the tasks. Cron Job Scheduling is a task scheduler in UNIX-like systems, which runs shell commands at specified intervals.

If we want to schedule tasks that will be executed every so often, we need to edit the Crontab. Crontab is a file that contains a list of scripts that will run periodically. Cron is a task scheduler daemon which runs scheduled tasks at specific intervals. Cron Job Scheduling uses the configuration file called crontab, also known as cron table, to manage the scheduling process. Crontab contains Cron Jobs, each related to a specific task. Cron jobs are composed of two parts.

1. Cron expression
2. Shell command to be run

* * * * * shell command to run

So what we do here is create a command using Laravel Console and then schedule that command at a particular time. When using the scheduler, you only need to add the following Cron entry to your server.

First, we download the freshlaravel and then start working on the example.

Step 1: Configuring the Laravel

Type the following to generate boilerplate of Laravel 5.6.

composer create-project laravel/laravel crontutorial --prefer-dist

Okay, now edit the .env file to configure the database.

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306
DB_DATABASE=cron
DB_USERNAME=root
DB_PASSWORD=

Now, migrate the tables into the database.

php artisan migrate

Step 2: Create User Authentication

Laravel provides Authentication system out of the box. Just hit the following command.

php artisan make:auth

It will generate authentication scaffolding.

See also  How to Send Email Using Queue in Laravel?

Next step, start the Laravel development server using the following command.

php artisan serve

Go to this URL href=”http://localhost:8000/register Register one user.

Step 3: Create Laravel Artisan Command

We use the make:console Artisan command to generate a command class skeleton to work with. In this application, we will just send one email to the owner telling that, we have these number of users registered today. So type the following command to generate our console command.

php artisan make:command RegisteredUsers --command=registered:users

The above command will create a class named RegisteredUsers in a file of the same name in the app/Console/Commands folder. We have also picked a name for the command via the command option. It is the name that we will use when calling the command. Now, open that command file RegisteredUsers.php.

/**
  * The console command description.
  *
  *
  * @var string
  */
  protected $description
 =
 'Send an email of registered users';

We have just changed the description of the command. Now, we need to register this command inside app >> Console >> Kernel.php file.

/**
  * The Artisan commands provided by your application.
  *
  * @var array
  */
  protected $commands = [

      'App\Console\Commands\RegisteredUsers',
  ];

Go to the terminal and hit the following command.

php artisan list

You can see in the list that your newly created command has been registered successfully. We just now to call in via Cron Job and get the job done. Now, write the handle method to get the number of users registered today.


// RegisteredUsers.php
/**
  * Execute the console command.
  *
  *
 @return mixed
  */
  public function handle()
  {
       $totalUsers = \DB::table('users')
                 ->whereRaw('Date(created_at) = CURDATE()')
                 ->count();
  }

Next step, we need to send an email that contains that totalUsers. So let’s create a mail class.

See also  What is Flutter? The Ultimate Guide for Beginners

Step 4: Create a Mailable Class to Send the Mail

Type following command to generate mail class.

php artisan make:mail SendMailable

So, It will create this file inside App\Mail\SendMailable.php. Now, this class contains one property, and that is count. This count is the number of users that registered today. So SendMailable.php file looks like this.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendMailable extends Mailable
{
    use Queueable, SerializesModels;
    public $count; 
    
    /**
    * Create a new message instance. 
    * 
    * @return void
    */
    public function __construct($count)
    {
        $this->count = $count;
    } 
    
    /**
    *
    * Build the message. 
    * 
    * @return $this 
    */
    public function build()
    {
        return $this->view('emails.registeredcount');
    }
}

Also, define the view for this mail at resources  >> views >> emails >> registeredcount.blade.php file. The mails folder is not there, so need to create one and then add the view registeredcount.blade.php.


<div>
     Total number of registered users for today is: {{ $count }}
</div>

Now, add this mailable class inside RegisteredUsers.php file.

// RegisteredUsers.php

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command; 
use Illuminate\Support\Facades\Mail; 
use App\Mail\SendMailable;
class RegisteredUsers extends Command
{
    /**
    * The name and signature of the console command.
    *
    * @var string
    */
    
    protected $signature = 'registered:users';
    
    /**
    * The console command description.
    *
    * @var string
    */
    
    protected $description = 'Send an email of registered users';
    
    /**
    * Create a new command instance.
    *
    * @return void
    */
    
    public function __construct()
    {
        parent::_construct();
    }
    
    /**
    * Execute the console command.
    *
    * @return mixed
    */
    
    public function handle()
    {
        $totalUsers = \DB::table('users')
            ->whereRaw('Date(created_at) = CURDATE()')
            ->count();
        Mail::to('*********')->send(new SendMailable($totalUsers));
    }
}

For sending a mail, we used Mailtrap. You can quickly signup there. It is free for some usage. It fakes the email, so it is convenient to test our application.

Now, type the following command to execute our code. Let us see that if we can get the mail.

php artisan registered:users

we are getting the email that is saying that a Total number of registered users for today is: 1. Now schedule this command via Cron Job.

See also  A Complete Guide to Events and Listeners in Laravel

Step 5: Scheduling the Commands

Let’s schedule a task for running the command we just built.

Our task, according to its usage, is supposed to be run once a day. So we can use the daily() method. So we need to write following code in the app  >>  Console  >>  Kerne.php file. We will write the code inside schedule function.

If you want to more info about task scheduling, then please refer the documentation.

// Kernel.php

    /**
    * Define the application's command schedule.
    *
    * @param \Illuminate\Console\Scheduling\Schedule $schedule
    * @return void
    */
    
    protected function schedule (Schedule $schedule)
    {
        $schedule->command('registered:users') 
                 ->everyMinute();
    }

When using the scheduler, you only need to add the following Cron entry to your server.

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

For us in localhost, we will hit the following command to get the mail of users.

php artisan schedule:run

After a minute, we can see that we are getting one mail that contains some users registered today. You can see more time interval here. So this is how you can configure the Cron Job Scheduling in Laravel. Finally, our Laravel Cron Job Scheduling Tutorial is over.

Wants to learn more about Laravel? We are providing complete solutions related to Laravel for your Websites and we have hire dedicated Laravel developers. Contact us to know more about the Cron job in Laravel.

    Need an IT Experts? Get a Free Consultation!

    lets start your project

    Related Articles