Table of Contents
Setting up a Cron Job in Laravel is an essential task for any web application that requires automated, scheduled tasks. In this article, we will explore how to set up a Cron Job in Laravel using the built-in Task Scheduler. By following this step-by-step tutorial on how to set Cron Job in Laravel, you will have a clear understanding of how to use the Task Scheduler to automate your application's tasks and improve its efficiency.
The Task Scheduler in Laravel provides a fluent, expressive API for defining tasks and the schedules on which they should run. With Cron, you can run tasks at specific times or intervals, such as running backups, sending emails, or updating your application's data.
By the end of this article, you will have a comprehensive understanding of how to set up a Cron Job in Laravel using the Task Scheduler. Whether you are building a new Laravel application or maintaining an existing one, this tutorial will help you automate your application's tasks and improve its efficiency.
Running a task at a particular time in future is called task scheduling. Cron jobs schedule tasks on a server. Handling cron jobs in Laravel is done using the Laravel command scheduler. The configuration happens in the app/Console/Kernel.php
inside the schedule
method.
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
The command scheduler runs one cron entry in your Laravel application at a time.
You can inspect the scheduled tasks and their next running time using the schedule:list
and run the scheduler using the schedule:work
artisans, respectively.
php artisan list # view all artisan commands
php artisan schedule:list
php artisan schedule:work
The schedule:work
method runs a task locally in the foreground until you manually stop the process ctrl+c
.
The schedule:run
method evaluates all tasks on the server and determines when they should run. A single cron entry on the server initiates the command. You can create and manage cron entries with Laravel Forge.
Different methods to set cron in laravel
There are several methods to set up a cron job in Laravel, depending on the environment and hosting platform. Here are a few common methods:
- Using the Laravel Task Scheduler: Laravel provides a built-in task scheduler that allows developers to define their scheduled jobs using a fluent, expressive syntax. This method is the most common and recommended way to set up a cron job in Laravel.
- Using a server cron job: Developers can set up a server cron job to run a specific command at specified intervals. This method requires SSH access to the server.
- Using a third-party scheduling service: Developers can also use third-party services like AWS Lambda or Google Cloud Functions to schedule their jobs.
- Using a cron job manager: There are several third-party cron job managers available, like Jenkins or Cronitor, which provide a visual interface for managing and scheduling cron jobs.
Example-1: Creating a Laravel Artisan Command for Reminder Tasks
make the command
php artisan make:command TodoToday
This is a sample code for creating an artisan command in Laravel that can be used to set a cron job. The command is called "TaskCommand
" and its purpose is to remind the user about a must-do task. It is defined in the "app/Console/Commands" directory and can be accessed through the "php artisan todo:today
" command.
When executed, the handle()
method of the TaskCommand
class will be called and it will display the message "set cron in Laravel using artisan command
". This command can be further customized to perform any task that needs to be executed regularly on a scheduled basis. By setting up a cron job using this command, the user can automate the execution of the task and ensure its timely completion without the need for manual intervention.
//in app/Console/Commands/TaskCommand
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class TaskCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'todo:today';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Artisan command to remind you about a must-do task.';
/**
* Execute the console command.
*/
public function handle(): void
{
echo "set cron in Laravel using artisan command\n";
}
}
set cron
protected function schedule(Schedule $schedule): void
{
$schedule->command('todo:today')->everyMinute();
}
How to Delete Database Records on a Schedule Using Laravel Cron
This code demonstrates how to use Laravel's cron scheduler to delete database records on a schedule. The schedule
method is used to define the task to be executed, which in this case is a closure that deletes all records from the tasks
table. The daily
method is then used to specify that the task should run once per day. This code can be modified to delete records from other tables or to run the task at a different interval, such as hourly, weekly, or monthly.
public function schedule(Schedule $schedule): void
{
$schedule->call(function () {
DB::table('tasks')->delete();
})->daily();
}
The scheduler encloses a callback function, which queries the database every day and deletes records in the tasks
table using the DB
facade. daily()
is one of the frequency periods. You can nest multiple frequency periods to control when the scheduler runs.
$schedule->command('calc')
->weekdays()
->hourly()
->timezone('America/Chicago')
->between('14:00', '17:00');
For example, the calc
command runs on weekdays, every hour between 2 pm and 5 pm in the America/Chicago time zone. Besides, you can prevent task overlap by chaining the withoutOverlapping(<minutes>)
or run tasks simultaneously using runInBackground()
method.
$schedule->command('calc')
->weekdays()
->hourly()
->timezone('America/Chicago')
->between('14:00', '17:00')
->withoutOverlapping()
-><code>runInBackground();
The withoutOverlapping()
method makes the calc
command wait for the previous command to finish running.
Example-2: Send a daily email to users who have registered in the last 24 hours:
Execute below command which will create a new file in the app/Console/Commands
directory named DailyUserRegistrationEmailCommand.php
.
php artisan make:command DailyUserRegistrationEmailCommand
In the handle
method of the DailyUserRegistrationEmailCommand
, add the logic to retrieve the list of users who have registered in the last 24 hours and send them an email.
public function handle()
{
$users = User::where('created_at', '>=', now()->subDay())->get();
foreach ($users as $user) {
Mail::to($user->email)->send(new DailyUserRegistrationEmail($user));
}
}
Create a new mailable class by running the command php artisan make:mail DailyUserRegistrationEmail
in your terminal. This will create a new file in the app/Mail
directory named DailyUserRegistrationEmail.php
.
In the build
method of the DailyUserRegistrationEmail
mailable class, define the email template and data to be sent to the user.
public function build()
{
return $this->view('emails.daily_user_registration')
->with([
'user' => $this->user,
]);
}
In the schedule
method of the app/Console/Kernel.php
file, define the schedule to run the DailyUserRegistrationEmailCommand
once per day at a specific time.
protected function schedule(Schedule $schedule)
{
$schedule->command('email:daily_user_registration')->dailyAt('09:00');
}
Finally, run the command crontab -e to open the crontab file and add the following entry to run the Laravel scheduler every minute:
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
This will ensure that the Laravel scheduler is executed every minute and will run any scheduled commands defined in the schedule
method of the Kernel.php
file.
Summary
In Laravel, the Task Scheduler allows you to automate various tasks such as running artisan commands or calling functions on a schedule. You can set up the Task Scheduler by defining scheduled tasks in the schedule
method of the App\Console\Kernel
class.
There are several methods available to set the schedule for a task, such as daily
, weekly
, hourly
, everyMinute
, and more. You can also set the timezone, specify a start and end time for the task to run, and prevent overlapping tasks.
One common use case for the Task Scheduler is to automate the deletion of database records on a schedule using Laravel Cron. By defining a scheduled task to run an artisan command or call a function that deletes the records, you can ensure that your database stays clean and free of unnecessary data.