Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

How to Scheduling Task using Cron Job in Laravel Application

Laravel Cronjob offers an elegant Task Scheduling or Laravel Cronjob Scheduling mechanism.

Applications require some tasks to be run periodically on the server. It could be creating backups or generating site traffic reports, sending promotional emails, or optimizing the database.

Step1- Open command prompt or Git Bash on xampp/htdocs directory

Step2- Create Laravel New Project write this command

composer create-project --prefer-dist laravel/laravel devopsschool "5.8.*"

Step3- Move to project directory on git bash

cd devopsschool

Step4- For User Authentication write this command

php artisan make:auth

Step5- Create Database in Mysql Server

Step6- Set Mysql Server Username ,Password and Database Name in .env file

DB_DATABASE = devopsschool
DB_USERNAME = root
DB_PASSWORD =

Step7- Migration of Tables in Database

php artisan migrate

Step 8- Create the Laravel Artisan Command.
We use the make: console Artisan command to generate a command class skeleton to work with.

In this application, we will send one email to the owner telling us 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.

Step 9- 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.

protected $description = 'Send an email of registered users';

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

protected $commands = [
        'App\Console\Commands\RegisteredUsers',
    ];

Step 11 – We just now to call in via CronJob and get the job done. Now, write the handle method to get the number of users registered today.

public function handle()
{
$totalUsers = \DB::table('users')
->whereRaw('Date(created_at) = CURDATE()')
->count();
}

Step 12 – we need to send an email that contains that totalUsers. So let’s create a mail class

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.

Step 13 – 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');
   }
}

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

Total number of registered users for today is: {{ $count }}

Step 15- Now, add this mailable class inside the RegisteredUsers.php file.

Mail::to(Config::get('app.MAIL_FROM'))->send(new SendMailable($totalUsers));

Step 16- For sending a mail, I have 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.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your-username
MAIL_PASSWORD=your-password
MAIL_ENCRYPTION=null
MAIL_FROM=info@devopsschool.com
MAIL_FROM_NAME=DevopsSchool

Step 17- Configure MAIL_FROM and MAIL_FROM_NAME on config/app.php

'MAIL_FROM' => env('MAIL_FROM', 'not found in .env file'),
'MAIL_FROM_NAME' => env('MAIL_FROM_NAME', 'not found in .env file'),

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

php artisan registered:users

Step 19-Task Scheduler in Laravel
Task Scheduler in Laravel executes the artisan command, shell, or a callback periodically on the defined time. To do this, we use the schedule method in app/Console/Kernel.php, as we discussed earlier.

protected function schedule(Schedule $schedule)
{
$schedule->command('registered:users')
->daily();
}
Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)