TechnologyWeb 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 a specific time, you will need a task scheduling mechanism to take care of the tasks. Cronjob Scheduling is a task scheduler in UNIX-like systems, used by Laravel developers, which runs shell commands at specified intervals.

What is a Cronjob?

Cron is time-based job scheduling in the Unix operating system. It runs periodically at fixed times, dates, and intervals. It is mainly used for automation.

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. Cronjob 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.

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 this 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 command’s description. Now, we need to register it inside the 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. 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  How to Implement Database Migration In CodeIgniter?

Step 4: Create a Mailable Class to Send the Mail

Type the following command to generate a 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 the 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 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 the 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.

See also  14 Software and Services Made Free During COVID-19

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.

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.

General Use Cases of Cronjob

  • Schedule backups of databases, important files, or the entire codebase.
  • Clean up log files and temporary files, or optimize databases.
  • Sync data between different servers, upload files to cloud storage, download files to local, etc
  • Implement custom monitoring in the system.
  • Create automatic reports and send them to respective members
  • Send emails for reminders, updates, or notifications.
  • Automatically restart services, and reboot servers after a specific period or actions.
  • Clear application and server cache to free the memory
  • Automated testing on a specified date and time
  • Automated social media posts, marketing campaigns through emails, SMS and push notifications

Backend Technologies for Cronjob

Backend technology includes server-side integration with web and mobile applications. All the backend technologies support the cron job functionality. This includes web server integration, database connections, data storage, server-side processing, and response to client requests via API.

Here are the few backend technologies that support the cron jobs.

1) PHP

PHP is a scripting language that is used to create dynamic web pages. It is free and open source. It is executed on the server which generates the html then sends it to the client. PHP is supported by all the major web servers including Apache, Nginx, and IIS.

See also  Integrating Security in SDLC to Enhance Website Architecture

2) .net

.Net is an open-source platform for developing desktop, web, and mobile applications that can natively run on any operating system .Net developement includes powerful tools and rich library support that help modern, scalable, and enterprise applications.

3) Node js

Nodejs is an open-source and cross-platform runtime environment. Node js allows creation of front end and back-end applications using javascript. A dedicated nodejs developers can help to run this function on a v8 javascript engine and executes javascript code outside a web browser.

4) Python

Python is a popular programming language for building web development, software development, automated tasks, and analyzing data. Python is widely used by data scientists and machine learning models because of its rich library support.

Important Roles of CronJob

Cronjobs can play a very important role in all industries automating backend tasks to improve efficiency and enhance user experience.

1) Travel Portal Development

  • In the travel portal development, cronjobs can automate the booking actions such as sending booking confirmation emails, booking confirmation SMS.
  • Reminders for upcoming trips.
  • We can ask the feedback after the completion of the trip.

2) Retail and E-commerce App Development

  • Automate Sales and Inventory report and send it to key persons.
  • It can be used in e-commerce app development to send automatic reminders and promotional emails to users who have left items in their cart. It will help users to complete their order process.

3) Banking and Finance App Development

  • Automate account statement and send it to the customer on a defined period.
  • Sending reminder emails and SMS notifications for upcoming load and credit card payments.
  • Automatically fetch the currency exchange rate from API and update in the current system for future financial transactions.

4) Healthcare App Development

  • Appointment reminder email, SMS, and healthcare mobile app notifications to customer.
  • Automate the daily medication reminder setup at a defined time.

5) Education App Development

  • Automate the exam reminders to the students in elearning app.
  • Attendance reports are generated automatically and sent to the teachers, students, and administrators regularly.

6) Media and Entertainment

  • Automatically publish pre-written articles, blogs, and social media posts at a specific time.
  • Automate the notification of payment renewal reminders, payment failure, and promotion of plans and packages.

7) Logistics and Supply chain

  • When the order is placed then automatically send packing and shipping instructions to the warehouse team.
  • Automatically send notifications when their order shipment status changes.

Ultimately, this is how the Cronjob is playing role in the Laravel technologies. So if you wants to explore and derived more about Laravel; than OneClick IT Consultancy can are providing complete solutions related to Laravel for your Websites and we have hire Laravel developers available to work for any custom solutions.

lets start your project

Related Articles