Cron job
We are using Laravel's built-in task scheduling, we just need to set up a Cron job on your live server to trigger the Laravel scheduler.
The Laravel scheduler itself uses the php artisan schedule:run command, which you need to run every minute to execute the scheduled tasks defined in your app/Console/Kernel.php
Here's how to set it up:
Step-by-Step Guide for a Live Server-
Step-1 Edit the Crontab File:
SSH into your live server.
Open the crontab file for editing by running:
=> crontab -e
Add the Laravel Scheduler Cron Entry:
Step-2 Add the following line to the crontab file:
=> * * * * * cd /path-to-your-laravel-project && php artisan schedule:run >> /dev/null 2>&1
This cron entry runs the Laravel scheduler every minute. Replace /path-to-your-laravel-project with the actual path to your Laravel application.
Step-3 Save and Exit:
Save the file and exit the editor (e.g., in nano, press CTRL+X, then Y, and then Enter).
Explanation:
cd /path-to-your-laravel-project: Changes the directory to your Laravel project.
php artisan schedule:run: Executes the Laravel scheduler command.
>> /dev/null 2>&1: Redirects all output to /dev/null to prevent cron from sending an email every minute.
Example:
If your Laravel project is located at /var/www/html/my-laravel-app, your cron entry would look like this:
=> * * * * * cd /var/www/html/my-laravel-app && php artisan schedule:run >> /dev/null 2>&1
Additional Notes:
Ensure that your web server user (e.g., www-data on Apache, nginx on Nginx) has the necessary permissions to run the php artisan schedule:run command and access your Laravel project directory.
You might want to check the server's timezone settings to ensure that the cron job runs at the expected times, especially if your scheduled tasks depend on specific time zones.
For debugging purposes, you can initially remove >> /dev/null 2>&1 to capture any output/errors from the cron job and ensure it's running correctly.
Conclusion:
By setting up a cron job to run php artisan schedule:run every minute, you can leverage Laravel's task scheduling features on your live server just like you do on your local environment. This approach ensures that all your scheduled tasks defined in app/Console/Kernel.php are executed as intended.
Last updated