In Laravel applications, automating tasks like sending emails, generating reports, or clearing caches at specific intervals is crucial. This is where Laravel cron job scheduling comes into game, allowing artisans to execute predefined commands or scripts automatically. This article will guide you through setting up and managing cron jobs in Laravel, leveraging its powerful scheduling feature
Laravel Setup for Cron Job Scheduling
To begin scheduling tasks in Laravel, ensure you have a working Laravel application set up. If not, install Laravel using Composer.
composer create-project --prefer-dist laravel/laravel cron-job-demo
cd cron-job-demo
Create New Command
In this step, we need to create our custom artisan command. That command will execute with task scheduling cron job. so, let’s run bellow command to create new custom command.
php artisan make:command DemoCron --command=demo:cron
Now let’s modify this command file.
app/Console/Commands/DemoCron.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class DemoCron extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'demo:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
Log::info("Hello From Command demo:cron!");
}
}
Register Scheduler
In this step, we need to define our commands in routes/console.php file with time when we want to run our command like as bellow functions that used to schedule our command or task
So let’s schedule our task
routes/console.php
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();
Schedule::command('demo:cron')->everyMinute();
now we are ready to run our cron command, so you can manually check using following command of your cron. so let’s run bellow artisan command:
php artisan schedule:run
After run above command, you can check log file where we already print some text. so open you your log file it looks like as bellow:
storage/logs/laravel.php
Refrences
* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
OR
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Source Code
https://github.com/techsoucedev/cron-job-demo