Create a custom command in Laravel application and implement as a Cron Job on a Webserver

Today every client wants to automate the business process with a web application. The Cron Job is one of the common automation features required in a web application.

The software utility Cron also is known as Cron job is a time-based job scheduler in Unix-like computer operating systems. Users that set up and maintain software environments use Cron to schedule jobs to run periodically at fixed times, dates, or intervals.

cron job

Laravel Cron Job Scheduling

Generally, web servers are supporting a Cron Job command with a script name. But in Laravel it’s different. In Laravel application have own Task schedular.

Laravel command scheduler allows the user an easy method to define a custom command. Your task schedule is defined in the app/Console/Kernel.php file’s schedule method.

Laravel Custom Artisan Command

First, create a custom command using the Laravel PHP artisan command.

1. Move to the Laravel application root folder.

2. Enter the artisan command on the command prompt.

Comand Syntax: php artisan make:command
Command Example: php artisan make:command SendInvoiceEmail

After executing the above-mentioned command, you will get a file in the app/console/Commands directory with the name ‘SendInoviceEmail‘.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mail;
class SendInvoiceEmail extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'monthly:invoices';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send monthly invoices emails to users.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
       $email_data = array (
			'to' => '[email protected]',
			'to_name' =>  'Joy Dave', 
			'subject' => 'Cron job testing',
			'from_email' => '[email protected]',
			'from_name' => 'Narinder Singh'
		);
		
		$email_data['email_content'] = 'cron job testing.';

		Mail::send([], $email_data, function($message)  use ($email_data) {
		
			$message->to($email_data['to'] , $email_data['to_name'])
			->subject($email_data['subject']);
			
			$message->from($email_data['from_email'] ,$email_data['from_name']);
			$message->setBody($email_data['email_content'], 'text/html');

		});
		
		// print output on command prompt.
		$this->info('test cron email');
    }
}
 

Update the command file code according to your requirements. In the above example, we are sending a test email.

protected $signature = 'command:name';

In the signature, variable replaces the words command:name with your command.

protected $description = ‘Command description’;

Description of your custom command.

Finally, the handle() function that is called whenever you execute this command. This function contains your custom code.

3. Now register your command with Laravel kernel.
Go to app/console/kernal.php and replace the following code:

protected $commands = [
        //
		Commands\SendInvoiceEmail::class
    ];
 protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
		$schedule->command('monthly:invoices')->daily();
    }

4. Now check your custom created command on the command prompt.

Run the following command. php artisan list

To make execution on a specific time interval. Set the schedule function in the kernal.php file. For a detailed check Laravel schedule frequency options

Setup Cron Job on the server

Every web server has a different UI interface for the Cron Job setup. The following command is generally used on every server. Kindly check your server documentation for more detail.

php artisan schedule:run >> /dev/null 2>&1

Tips and tricks

Please keep in mind. If your server has different PHP versions installed. Laravel support PHP 7.0 and above versions.

So you need to update the artisan command according to the PHP version.
For example on a HostGator cpanel cron command for PHP 7.2

/opt/cpanel/ea-php72/root/usr/bin/php /home1/stelidevara/public_html/artisan schedule:run >> /dev/null 2>&1

In above command “/opt/cpanel/ea-php72/root/usr/bin/php“. It is an active path of PHP 7.2

/home1/stelidevara/public_html/artisan“. This is Laravel artisan command path.

But sometimes, the command does not execute, because the artisan command path is not found. In such cases we need to refine the command. The following command might works for you much better.

cd public_html && /opt/cpanel/ea-php72/root/usr/bin/php artisan schedule:run >> /dev/null 2>&1

I hope you learn something from this blog post. Hit social share buttons to inspire me to keep posting such articles.