
Laravel includes a built-in task scheduling system that simplifies managing recurring tasks. You can use Laravel cron jobs to schedule tasks with multiple PHP syntax elements directly within your Laravel application instead of manually adding entries to the system crontab. The Laravel task scheduler supports flexible frequencies, timezones, output management, and advanced options, allowing you to automate cleanups, generate reports, and send email notifications within your Laravel application.
This article explains how to configure Laravel cron jobs. You will set up the Laravel task scheduler, create custom commands, and a cron job to automatically trigger scheduled tasks in your Laravel project.
Before you begin, you need to:
Tasks are scheduled operations that execute automatically at defined intervals in Laravel. Tasks include artisan commands you define to run on a schedule in a Laravel application. Follow the steps below to define a new scheduled command, and verify its execution in Laravel.
Navigate to your Laravel project directory such as /var/www/laravelapp.
Long list the directory to verify the group ownership details.
Your output should be similar to the one below.
The www-data group owns the /var/www/laravelapp directory, allowing any user in the group to access files in the Laravel project directory.
Verify the current user you are logged in as.
Your output should be similar to the one below.
Add the user to the www-data group to enable access to the Laravel project directory. Replace linuxuser with your actual username.
Grant the user ownership privileges to the /var/www/laravelapp directory.
Print your working directory and verify that it's the root Laravel project directory.
Output:
Back up the routes/console.php file.
Create a new routes/console.php file using a text editor such as nano.
Add the following code to the routes/console.php file to define a new scheduled task.
Save and close the file.
The above task configuration logs the date and time at every second to the Laravel log file.
Trigger the Laravel scheduler to verify that the task is active.
Your output should be similar to the one below.
The scheduled task is active and running based on the above log output.
Press Ctrl + C to stop the Laravel task.
Laravel Artisan commands allow you to define reusable, custom CLI commands to encapsulate complex or repetitive tasks. Laravel commands can be scheduled or triggered manually using the artisan command-line tool. Follow the steps below to create and test a custom Artisan command in Laravel.
Create a new CacheClearCommand Artisan command.
The above command generates a new file in the app/Console/Commands/ directory.
Open the generated CacheClearCommand.php file using a text editor such as nano.
Add the following code to the CacheClearCommand.php file.
Save and close the file.
The above application code defines a new app:clear-cache command that clears the application cache and logs the result to the laravel.log file in the storage/logs/ directory.
Run the following command to clear the application cache.
Output:
The above command output confirms that the custom Artisan command is working correctly.
The Laravel task scheduling system allows you to automate command executions at defined intervals with a user-friendly syntax. Follow the steps below to schedule the app:clear-cache command you created earlier to run every two seconds.
Back up the routes/console.php file again.
Create the routes/console.php file again.
Add the following code to the routes/console.php file.
Save and close the file.
The above code schedules the app:clear-cache command to run every two seconds. The schedule will only run when the schedule:run command executes.
Laravel offers several methods to define the frequency and behavior of scheduled tasks. Below are the commonly used scheduling options you can add to your routes/console.php file to run tasks.
Monthly:
The above schedule runs the app:clear-cache command once every month.
Daily at a specific time:
Runs the task daily at a specific time, such as 8:00 AM.
Daily:
Runs the task once every day at midnight.
Weekly on a specific day and time:
Runs the task on a specific day each week at a set time. Based on the above example, the task runs every Monday at 8:00 AM.
Every hour:
Runs the task once every hour.
Every five minutes:
Runs the task every 5 minutes.
Every minute:
Runs the task once every minute.
Using a custom cron expression:
Runs the task once every 5 minutes from Monday to Friday.
Log the output to a file:
Runs the task and appends the output to a log file.
Email task output:
Sends the task's output to an email such as admin@example.com.
Email only on failure:
Sends an email if the task fails.
Laravel provides several advanced scheduling methods to enhance the functionality of scheduled tasks. These methods allow you to customize the behavior of each scheduled task to meet your project requirements. The supported advanced Laravel scheduling methods include the following.
Prevent task overlaps when a task runs longer than expected.
Use withoutOverlapping() to ensure that a task does not overlap with the next scheduled instance if it takes longer to complete.
Ensure tasks run on only one server in a multi-server environment.
Use onOneServer() to ensure the task runs on only one server in a multi-server setup.
Run the tasks in the background.
Use runInBackground() to run tasks in the background and avoid blocking other processes.
Run the tasks even during application maintenance mode.
Use evenInMaintenanceMode() to run tasks even when the application is in maintenance mode.
Run tasks only when certain conditions are met.
Use when() to run tasks based on specific conditions, such as the number of users in the application.
Specify time boundaries for when tasks can run.
Use between() to specify a time range in which the task should run.
Handle task success and failure events.
Use onSuccess() and onFailure() to define actions based on the task's outcome.
You can automate Laravel cron jobs with cron by creating a new task for the Laravel scheduler. Follow the steps below to automate Laravel cron jobs by modifying the system crontab file.
Open the crontab editor.
Choose your preferred text editor such as nano when prompted.
Add the following cron entry to the file to run the Laravel scheduler every minute.
The above cron task runs the scheduler at every minute within the Laravel project directory. The php artisan schedule:run command starts the Laravel scheduler, and the output is redirected to /dev/null to run the cron job silently without displaying any output.
Run the following command to list all cron jobs scheduled for your user and verify that the Laravel task is available.
Your output should be similar to the one below:
Follow the steps below to verify that your scheduled tasks appear in the scheduler list and the automated cron job is working correctly.
Print your working directory and verify that it's the root Laravel project directory.
Output:
List all scheduled tasks in your Laravel project.
Your output should be similar to the one below.
The above output verifies the scheduled time, command, and status of each task.
Monitor the Laravel log file and verify that the scheduled tasks are active.
You output should be similar to the one below if the cron job is actively running in your project.
The timestamps in the above output verify that the scheduled task is running as expected.
Press Ctrl+C to stop the log file output.
You have configured Laravel cron jobs using the built-in task scheduler and automated tasks to run at specific intervals. You can automate recurring tasks in Laravel and efficiently manage the scheduled tasks for execution at a specific time. For more information and advanced scheduling tasks in Laravel, visit the Laravel documentation.
0 Comments
Be the first to comment and share your perspective with the community.