Task Scheduling in Laravel - Using Laravel’s Built-in Scheduler

Task Scheduling in Laravel - Using Laravel’s Built-in Scheduler

1. Introduction to Laravel Task Scheduling

Laravel provides a built-in task scheduler that allows you to automate commands and jobs without relying on external cron jobs.

2. Setting Up the Laravel Scheduler

First, ensure your Laravel application has a cron job set up by adding this to your server’s crontab:

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

3. Defining Scheduled Tasks

In the app/Console/Kernel.php file, you can define tasks inside the schedule method:

protected function schedule(Schedule $schedule)
{
    $schedule->command('emails:send')->dailyAt('08:00');
}

4. Scheduling Artisan Commands

You can schedule built-in or custom Artisan commands:

$schedule->command('queue:work')->everyMinute();

5. Scheduling Shell Commands

You can also execute shell commands using the scheduler:

$schedule->exec('php artisan migrate')->weekly();

6. Task Frequency Options

Laravel provides various scheduling frequencies:

  • ->everyMinute()
  • ->hourly()
  • ->daily()
  • ->weekly()
  • ->monthly()
  • ->yearly()

7. Preventing Task Overlaps

To ensure a task doesn’t overlap, use the withoutOverlapping() method:

$schedule->command('emails:send')->daily()->withoutOverlapping();

8. Logging Scheduled Tasks

To log scheduled task executions, you can use:

$schedule->command('emails:send')->daily()->appendOutputTo(storage_path('logs/schedule.log'));

9. Running Tasks on Specific Conditions

Laravel allows you to run scheduled tasks conditionally:

$schedule->command('backup:run')->daily()->when(fn() => date('D') === 'Sun');

10. Conclusion

Laravel’s task scheduler simplifies job automation without requiring complex cron jobs. Implement it in your application to streamline repetitive tasks.

Published by Developer Sahayak - Helping Developers Solve PHP, Laravel, and Drupal Issues.

0 Comments