You can create a Cron job in Laravel for task scheduling. Generally, a cron executes the scheduled task at the specified time interval. This will process the task and execute it. It will trigger automatically to finish the execution. When you are on the live server, there is the option to create a cron job. That will take any URL in the form of an endpoint in which the defined process will be executing. If we talk about Laravel, then it provides functionality for task scheduling. In this post, you will learn task scheduling in Laravel 8. I will demonstrate the cron job scheduler in Laravel. However, for this post, I will start from scratch by giving a cron job example in Laravel 8.
Prerequisites
This project will require the below configurations. So, I am assume you already have installed these tools.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
When you are ready, let’s create a new project first.
Create a Project For Task Scheduling in Laravel 8
I will be using the composer for the Laravel 8 installation. You can use the Laravel installer also, it is up to. Firstly, open the terminal or command prompt and hit enter the below command.
composer create-project --prefer-dist laravel/laravel task-schedule
After hitting the above command, the Laravel 8 installation will be started.
Hence, after creating the project, just go inside the project folder. Now, open it inside the editor.
So, In the next step, we will configure the database settings for this project.
Import and Export CSV and Excel File in Laravel 8
Database Configuration For Laravel 8 Project
In this project, for the database management operations, I am using MySQL command line. So, here, I am going to create the database by hitting the below command.
CREATE DATABASE task_scheduler;
Therefore, the above command will create the database.
After creating the database, move to the root directory of your project. Find the .env file and just add the database details as showing below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=task_scheduler
DB_USERNAME=root
DB_PASSWORD=root
Here, we are ready with the database connection. Now, let’s migrate the tables firstly.
php artisan migrate
The above command will migrate the tables.
Now, in the next step, we will create a custom command in Laravel 8.
How to Generate PDF File in Laravel 8 Using DOM PDF
Create a Custom Command in Laravel 8 For Task Scheduling
As we know, Laravel provides an option to create the custom command. This custom command can execute any process, tasks, queues, etc using the scheduler. So, you can create the custom command by hitting the below line.
php artisan make:command TaskCron --command=task:cron
Here, this command has generated a file in the path app/Console/Commands
. But, you can take a look at the below screenshot for the created command.
Hence, after creating the custom command, you will have to pass the command signature and description.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class TaskCron extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'task:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send Email to User Every Minute';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
return 0;
}
}
You can check the created custom commands using the artisan command.
Check Custom Command
To check the command list in Laravel, you can hit the below command in the terminal.
php artisan list
RESTful APIs For Todo App Using Passport Auth in Laravel 8
Create Email Class in Laravel 8
So, here, we will create an email class for sending emails to users. But, actually, for the cron, I will schedule the email.
php artisan make:mail SendEmail
The above command created a class inside the app/Mail directory.
After creating the mail class, we will add a few lines of code as showing below.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('admin@programmingfields.com')->view('email-template');
}
}
Finally, we defined sender email and a view for email template. So, here we will need one view to create for the email template.
How to Implement Invisible reCAPTCHA in Laravel 8
Create a View For Email Template
In the resources/views directory, create a view with the name email-template.php. Then put a basic email body as showing below.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 8 Task Scheduling Using Cron Job</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<p>Hello</p>
<p>This is a basic example of sending email through the laravel 8 cron job.</p>
<br/>
<p>Regards</p>
<p>Programming Fields</p>
</body>
</html>
Now, all set for email and email template. Now, in the next step, we have to set the task in the handle() method of the custom command.
Create Authentication in Laravel 8 Using Laravel Breeze
Cron Job Scheduler in Laravel 8
We have set the cron to execute in everyMinute(). Now, we have to define the task in the handle() method of the created command (TaskCron.php). So, just add the below snippet there.
<?php
namespace App\Console\Commands;
use App\Mail\SendEmail;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class TaskCron extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'task:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send Email to User Every Minute';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$users = User::all();
if (count($users) > 0) {
foreach($users as $user) {
Mail::to($user->email)->send(new SendEmail);
}
}
}
}
After putting the task in the TaskCron.php file, we can run the cron. But don’t forget to configure the email settings before sending email.
Here, I already configured the email settings in the .env file.
MAIL_MAILER=smtp
MAIL_HOST={{MAIL_HOST}}
MAIL_PORT={{MAIL_PORT}}
MAIL_USERNAME={{MAIL_USERNAME}}
MAIL_PASSWORD={{YOUR_PASSWORD}}
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS={{MAIL_FROM_ADDRESS}}
MAIL_FROM_NAME="${APP_NAME}"
User Authentication in Laravel 8 Using UI Auth Package
Run Custom Command For Cron
Therefore, after the configuration, you can run the application and check the result. Here, in the local server, we will have to run this custom command manually. So, to run the custom command, here, we will have to hit the below line.
php artisan task:cron
The above command will hit the custom command (TaskCron.php). Inside this custom command, we have already defined the functionality to send email. So, in the response, you will get mail sent successfully.
You can set the different intervals for the cron job. For more details, you can go to the official documentation of Laravel. But, here, I listed some methods with descriptions.
Cron Job Intervals in Laravel 8
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 |
->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 |
->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 |
Remove Uploaded Image in Laravel 8 From Public Folder
Schedule Cron Job on Server
If you want to run the Laravel cron on the online server then you will have to specify the full path as showing below.
* * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Conclusion
In this post, we learned to create the custom command in Laravel. The custom command needs to be register in the console kernel. Here, we specified the schedule time on which the command will perform the action. In the action, we defined the functionality to send email to the users. So, for that, we created a mail class, and configured the email setting. Hence, I hope, you will find it helpful for your real projects. If you get any issue on scheduling a task in Laravel then don’t put your comments in the below comment section.
Robert Allan says
That’s helpful but I’d got most of that worked out already. Any chance of seeing a scheduled command running Laravel Jobs in a Laravel queue?
Umesh Rana says
If you have already created a command for scheduling jobs in the form of a queue then the process is the same. Where you are facing problems?
Martin says
Well explained! It helps me a lot.