How to schedule tasks in Laravel: A developer’s guide

Updated: January 22, 2024 By: Guest Contributor Post a comment

Introduction

Task scheduling is an essential aspect of modern web application development. In Laravel, one of the most popular PHP frameworks, task scheduling is both powerful and simplistic allowing developers to fluently and expressively define their command schedule within their application. This tutorial will take you through the process of setting up task scheduling and provide examples of common scheduling scenarios.

Before we dive into the Laravel Scheduler, ensure that you’re running Laravel 5.0 or higher as the task scheduling features were introduced in this version. The scheduler relies on cron, a time-based job scheduler in Unix-like operating systems, so your server must have cron running.

Configuring Task Scheduler

The entry point of the scheduler is the app/Console/Kernel.php file. This file contains the schedule method, which is where you will define all your scheduled tasks.


protected function schedule(Schedule $schedule)
{
  $schedule->command('inspire')->hourly();
}

Once you have defined your schedules, you need to have a single cron entry on your server that runs the Laravel command scheduler every minute.

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

Types of Scheduled Tasks

Scheduled tasks can be commands, shell commands, or callback functions. Below are some examples:

Artisan Commands

Scheduling an Artisan command to run every day at midnight:


$schedule->command('database:backup')->dailyAt('00:00');

Queued Commands

If you need to queue the command for background execution, you can use the queue method:


$schedule->command('email:send --force')->daily()->queue();

Executing Shell Commands

You can also define shell commands to run at a scheduled interval:


$schedule->exec('node /home/path-to-node-script.js')->everyFiveMinutes();

Managing Schedules

Laravel provides various methods for controlling the schedule frequency as well as constraints that determine when the task should be executed.

Method Chaining for Frequent Tasks

Method chaining can be used for specific frequencies:


$schedule->command('reports:generate')->weekly()->mondays()->at('15:00');

Environment and Maintenance Mode Constraints

Scheduled tasks can be constrained to only run in certain environments or when your application is not in maintenance mode:

$schedule->command('email:customers')
         ->daily()
         ->when(fn () => ! app()->isDownForMaintenance());

$schedule->command('email:customers')
         ->daily()
         ->environments(['production', 'staging']);

Preventing Task Overlaps

Laravel prevents task overlap out of the box by using the withoutOverlapping method:


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

Task Output

To output the results of scheduled tasks to a file or e-mail them, use the sendOutputTo and emailOutputTo methods respectively:

$schedule->command('report:generate')
         ->daily()
         ->sendOutputTo($filePath);

$schedule->command('report:generate')
         ->daily()
         ->emailOutputTo('[email protected]');

Handling Failing Scheduled Tasks

You can set up e-mail notifications for when a scheduled task fails by using the pingOnFailure method, which integrates with services like Laravel’s own Envoyer:

$schedule->command('report:generate')
         ->daily()
         ->pingOnFailure('https://envoyer.com/heartbeat/url');

Testing Scheduled Commands

To test the execution of your scheduled tasks, you can execute them manually using Artisan:


php artisan schedule:run

By the end of this guide, you should have a solid understanding of how to schedule tasks in Laravel. The simplicity of Laravel’s scheduling allows you to keep your scheduled task management and definitions within your codebase, leading to more readable and maintainable code.

Conclusion

Task scheduling in Laravel provides a robust solution for automating background tasks such as sending emails, database backups, and even pinging external services. With this elegant and easy-to-use functionality, Laravel continues to be a leading choice for developers seeking a full-featured yet accessible PHP framework.