Laravel is a powerful and efficient PHP framework that simplifies development with a wide range of built-in features. Among them, task scheduling is a practical tool that allows developers to automate repetitive actions at set intervals. In this article, we explore two main ways to implement scheduled tasks in Laravel: using the Crontab command-line utility and Laravel’s internal scheduling system.
Crontab is a Unix-based tool that allows commands or scripts to be run automatically at specified times and intervals. Laravel tasks can be executed via Crontab by running custom shell scripts that trigger Laravel Artisan commands.
Create a shell script (e.g., test.sh) in the root directory of your Laravel project with the following content:
#!/bin/bash
cd /path/to/project && php artisan my:task
Make sure the path points to your Laravel project root so the command executes properly.
Open your terminal and enter the Crontab editor using:
<span class="fun">crontab -e</span>
Then, add the following line to schedule your task:
<span class="fun">*/10 * * * * /path/to/test.sh >> /path/to/log/crontab.log 2>&1</span>
This configuration runs the test.sh script every 10 minutes and appends the output to a log file.
Laravel offers a native way to define and manage scheduled tasks using its Artisan command scheduler, without relying directly on Crontab for each individual command.
In the app/Console/Kernel.php file, use the schedule method to define a scheduled task, like so:
// Execute the 'my:task' command every two minutes
$schedule->command('my:task')->everyTwoMinutes();
This sets the task to run every two minutes using Laravel’s scheduler.
Include your schedule definition in the Kernel class’s schedule method:
protected function schedule(Schedule $schedule)
{
$schedule->command('my:task')->everyTwoMinutes();
}
This ensures Laravel knows when and how often to run the specified command.
To manually trigger the scheduler and run due tasks, use the following command:
<span class="fun">php artisan schedule:run</span>
This command will evaluate all scheduled tasks and run any that are due.
This guide has explained two effective ways to handle scheduled tasks in Laravel. Crontab provides system-level scheduling and is suitable for broader server control, while Laravel’s internal scheduler is ideal for application-specific automation. Depending on your project needs, you can choose the method that best fits your workflow.