Throughout this tutorial, you will learn how to schedule a task in Laravel application using Cron Job.
Task Scheduling is an art of systematically set your priorities to achieve your goals on time, on the other hand, Cron Job is a software utility which is used to schedule a specific task to run periodically in the software application.
You can schedule a task with Cron job in laravel, in the same way, evoke it periodically. Luckily, laravel offers you a powerful task manager having said that you will see how to use it in laravel environment properly.
Also, you will get to know how to create a new artisan command, brevity about custom laravel command, how to register new task scheduler in laravel kernel file, how to handle task scheduler effectively not only but similarly how to run laravel task scheduler from the utter beginning.
Create Laravel Project
Begin with installing a new Laravel project for cron job scheduling task:
composer create-project laravel/laravel laravel-task-schedule-example --prefer-dist
Connect Laravel to Database
Add the database name, username and password in .env
file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=
Generate New Artisan Command
Artisan is a command-line interface that comes with Laravel; you can build your entire application with its useful command. Likewise, to create a new command, you can use the make: command
, It will generate a command class in the app/Console/Commands folder.
php artisan make:command DailyMessage
On the other hand, you can check the app/Console/Commands/DailyMessage.php file where you can register the new cron job command for task scheduling.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class DailyMessage extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:name';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
return 0;
}
}
Prepare Laravel Custom Command
Head over to app/Console/Commands/DailyQuote.php file, In the second place, Replace the current code with the given below code.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;
use App\Models\User;
class DailyMessage extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'daily:message';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send best wishes daily.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$messages = [
'A. A. Milne' => 'People say nothing is impossible, but I do nothing every day.',
'Abraham Lincoln' => 'Better to remain silent and be thought a fool than to speak out and remove all doubt.',
'Abraham Lincoln' => 'If I were two-faced, would I be wearing this one?',
'Al McGuire' => 'The only mystery in life is why the kamikaze pilots wore helmets.',
'Alan Dundes' => 'Light travels faster than sound. This is why some people appear bright until you hear them speak.',
'Albert Camus' => 'Nobody realizes that some people expend tremendous energy merely to be normal.'
];
// Setting up a random word
$key = array_rand($messages);
$data = $messages[$key];
$users = User::all();
foreach ($users as $user) {
Mail::raw("{$key} -> {$data}", function ($mail) use ($user) {
$mail->from('johnny@remotestack.io');
$mail->to($user->email)
->subject('Good monring!');
});
}
$this->info('Message sent.');
}
}
Register Task Scheduler Command
Till above we have generated and created a custom command to schedule task. Now, you have to register the new Task Scheduler command in app/Console/Kernel.php file.
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\DailyMessage::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('daily:message')
->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
If you use given below command then you can also see the command you just created:
php artisan list
cache
cache:clear Flush the application cache
cache:forget Remove an item from the cache
cache:table Create a migration for the cache database table
config
config:cache Create a cache file for faster configuration loading
config:clear Remove the configuration cache file
daily
daily:message Send best wishes daily.
db
db:seed Seed the database with records
db:wipe Drop all tables, views, and types
event
event:cache Discover and cache the application's events and listeners
event:clear Clear all cached events and listeners
event:generate Generate the missing events and listeners based on registration
event:list List the application's events and listeners
key
key:generate Set the application key
You can use below command to schedule your task with cron job:
php artisan daily:message
If everything goes well, this will be seen on your console screen:
Message sent.
Set Schedule Frequent with Multiple Options
As you remember, you used the everyMinute() frequency in schedule:
protected function schedule(Schedule $schedule)
{
$schedule->command('daily:message')
->everyMinute();
}
Having said that, there are innumerable schedules that you can assign to your cron tasks:
Schedule Frequency | Details |
---|---|
->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 |
Have a look on more task schedule frequency on Laravel.
Run Task Scheduler
You have two options to run task scheduler manually or automatically
So, begin first with manual method.
php artisan schedule:run
If worked properly then it will be displayed on your console:
Running scheduled command: '/usr/local/Cellar/php/7.4.10/bin/php' 'artisan' daily:message > '/dev/null' 2>&1
Have a look on the logs in storage/logs/laravel.php file.
Next, you can also automate the task scheduler for cron job.
Let’s automate the Laravel task scheduler:
SSH into your server to add additional Cron entries:
crontab -e
Now, add the complete path in in crontab file of your application:
* * * * * cd /your-app-path && php artisan schedule:run >> /dev/null 2>&1
The Laravel Cron Job tutorial is over now you know how to easily schedule a task in Laravel application.