Sling Academy
Home/PHP/How to schedule tasks in Laravel: A developer’s guide

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

Last updated: January 22, 2024

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.

Next Article: How to run background, heavy tasks in Laravel: An in-depth guide

Previous Article: How to create a shopping cart in Laravel

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array