Cron are used to schedule a service or task run periodically on specific time, date or intervals. In laravel we can Run Cron Job Scheduler same in the way we use to run in Unix system by adding the cron in crontab configuration but in laravel there is a standard way to create the schedulers and in production for all scheduler we need to create a single cron entry in crontab at 1 minute interval then in laravel we can configure it from multiple interval, time and date.
In this tutorial i will show you to use laravel Task schedulers to run a cron at 1 minute interval. For example you want to check the subscription on each day or you want to send notification to the users on a specific event on time then task scheduler come in the role to play the cron job functionality in laravel.
In this example we will insert in table in interval of 1 minute and also log it into laravel logs.
Let’s understand Run Cron Job Scheduler in laravel with step by step
Step 1: Create a fresh laravel project
Open a terminal window and type below command to create a new project
composer create-project --prefer-dist laravel/laravel blog
You can also read this to start with new project
Step 2: Register cron scheduler in Kernal.php
There is no need of any configuration to run the task scheduler in laravel if you want to quickly run a cron job in laravel then you can directly register it in app/Console/Kernel.php
file as follow
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Log;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('cache:clean')->hourly();
$schedule->call(function () {
Log::info("Cron:", "Running cron every minutes");
})->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
As you can see we have registered a call method in schedule method of kernel class as below
protected function schedule(Schedule $schedule)
{
// $schedule->command('cache:clean')->hourly();
$schedule->call(function () {
Log::info("Cron: Running cron every minutes", ["msg"=>"success"]);
//or you can call any library, helper and model from here
// /App/Models/User::where("is_verified","0")->delete();
})->everyMinute();
}
Here are the options for running the cron in frequency
Method | Description |
---|---|
->cron('* * * * *'); | Run the task on a custom cron schedule |
->everyMinute(); | Run the task every minute |
->everyTwoMinutes(); | Run the task every two minutes |
->everyThreeMinutes(); | Run the task every three minutes |
->everyFourMinutes(); | Run the task every four minutes |
->everyFiveMinutes(); | Run the task every five minutes |
->everyTenMinutes(); | Run the task every ten minutes |
->everyFifteenMinutes(); | Run the task every fifteen minutes |
->everyThirtyMinutes(); | Run the task every thirty minutes |
->hourly(); | Run the task every hour |
->hourlyAt(17); | Run the task every hour at 17 minutes past the hour |
->everyTwoHours(); | Run the task every two hours |
->everyThreeHours(); | Run the task every three hours |
->everyFourHours(); | Run the task every four hours |
->everySixHours(); | Run the task every six hours |
->daily(); | Run the task every day at midnight |
->dailyAt('13:00'); | Run the task every day at 13:00 |
->twiceDaily(1, 13); | Run the task daily at 1:00 & 13:00 |
->weekly(); | Run the task every Sunday at 00:00 |
->weeklyOn(1, '8:00'); | Run the task every week on Monday at 8:00 |
->monthly(); | Run the task on the first day of every month at 00:00 |
->monthlyOn(4, '15:00'); | Run the task every month on the 4th at 15:00 |
->twiceMonthly(1, 16, '13:00'); | Run the task monthly on the 1st and 16th at 13:00 |
->lastDayOfMonth('15:00'); | Run the task on the last day of the month at 15:00 |
->quarterly(); | Run the task on the first day of every quarter at 00:00 |
->yearly(); | Run the task on the first day of every year at 00:00 |
->yearlyOn(6, 1, '17:00'); | Run the task every year on June 1st at 17:00 |
->timezone('America/New_York'); | Set the timezone for the task |
You can read more about this here https://laravel.com/docs/9.x/scheduling#schedule-frequency-options
In laravel task scheduler we can also schedule a artisan command as follow
protected function schedule(Schedule $schedule)
{
$schedule->command('cache:clean')->hourly();
}
Or create a new command to handle the complete task scheduler logic in Command class.
Step 3: Test the schedular
Now, In the local environment we can test it easily by running the following command in terminal
php artisan schedule:work
and for run in production server you need to add it in crontab configuration so add it in cron tab as below
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Output in storage/logs/laravel.log:
[2022-05-18 17:29:00] local.INFO: Cron: Running cron every minutes {"msg":"success"} [2022-05-18 17:30:00] local.INFO: Cron: Running cron every minutes {"msg":"success"} [2022-05-18 17:31:00] local.INFO: Cron: Running cron every minutes {"msg":"success"}
Task scheduler hooks
Hooks are used to run before or after of any event for example we can run before
hook before processing of a call method and same as after method, to run the hook to run after the completion of cron job as follow
$schedule->command('cache:clean')
->daily()
->before(function () {
// The task is about to execute...
})
->after(function () {
// The task has executed...
});
OnSuccess and OnFailure in Task Schedular
Same as before after we can register OnSuccess and OnFailure hooks on job as below
$schedule->command('cache:clean')
->daily()
->onSuccess(function () {
// The task succeeded...
})
->onFailure(function () {
// The task failed...
});