Guide to Setting Up Laravel Cron Jobs

Aug 27, 2024

Notes on Setting Up a Cron Job in Laravel

Introduction

  • Overview of today's topic: Setting up a cron job in a Laravel application on a live server (Hostinger).

What is a Cron Job?

  • A cron job is a scheduled task that runs automatically at specified intervals.
  • Useful for repetitive tasks, such as:
    • Sending daily emails at a specific time
    • Performing tasks every minute, hour, or day without manual intervention.

Scheduling in Laravel

  • Laravel has an inbuilt scheduling feature for automating task execution.
  • Tasks can be executed:
    • Every minute
    • Daily
    • Monthly
    • Yearly

Setting Up a Cron Job in Laravel

Step 1: Create a Command

  • Go to the app/Console directory.
  • Create a test command (e.g., Membership:update).
  • Define the logic inside the handle function to fetch users from the database and update their status.

Step 2: Schedule the Command

  • Open Kernel.php in the app/Console directory.
  • Use the schedule method to specify when the command should run (e.g., every minute).
  • Format:
    $schedule->command('Membership:update')->everyMinute();  
    

Setting up Cron Job on Hostinger

Step 3: Access Hosting Dashboard

  • Navigate to the advanced options in the Hostinger dashboard.
  • Click on "Cron Jobs" to set up a new cron job.

Step 4: Create a Cron Job

  • Example: Set a cron job that runs every minute.
  • Use the following command:
    php /home/username/public_html/artisan schedule:run  
    

Step 5: Specify Path

  • Ensure the path is correct:
    • /home/username/public_html/ followed by the command location.

Testing the Cron Job

  • Monitor the execution of the cron job.
  • Refresh to check for updates in the database or output as expected.

Conclusion

  • Successful implementation of a cron job in a Laravel application can automate repetitive tasks.
  • Further videos will cover setting up cron jobs on localhost and server environments.

Call to Action

  • Like, share, and subscribe for more informative videos.