Task Scheduling

    In the past, you may have generated a Cron entry for each task you needed to schedule on your server. However, this can quickly become a pain, because your task schedule is no longer in source control and you must SSH into your server to add additional Cron entries.

    Laravel's command scheduler allows you to fluently and expressively define your command schedule within Laravel itself. When using the scheduler, only a single Cron entry is needed on your server. Your task schedule is defined in the file's schedule method. To help you get started, a simple example is defined within the method.

    When using the scheduler, you only need to add the following Cron entry to your server. If you do not know how to add Cron entries to your server, consider using a service such as Laravel Forge which can manage the Cron entries for you:

    This Cron will call the Laravel command scheduler every minute. When the schedule:run command is executed, Laravel will evaluate your scheduled tasks and runs the tasks that are due.

    You may define all of your scheduled tasks in the schedule method of the App\Console\Kernel class. To get started, let's look at an example of scheduling a task. In this example, we will schedule a Closure to be called every day at midnight. Within the Closure we will execute a database query to clear a table:

    1. <?php
    2. namespace App\Console;
    3. use DB;
    4. use Illuminate\Console\Scheduling\Schedule;
    5. use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
    6. class Kernel extends ConsoleKernel
    7. {
    8. * The Artisan commands provided by your application.
    9. *
    10. * @var array
    11. */
    12. protected $commands = [
    13. //
    14. ];
    15. /**
    16. * Define the application's command schedule.
    17. *
    18. * @param \Illuminate\Console\Scheduling\Schedule $schedule
    19. * @return void
    20. */
    21. protected function schedule(Schedule $schedule)
    22. {
    23. $schedule->call(function () {
    24. DB::table('recent_users')->delete();
    25. })->daily();
    26. }
    27. }

    In addition to scheduling using Closures, you may also using invokable objects. Invokable objects are simple PHP classes that contain an __invoke method:

    1. $schedule->call(new DeleteRecentUsers)->daily();

    Scheduling Artisan Commands

    In addition to scheduling Closure calls, you may also schedule and operating system commands. For example, you may use the command method to schedule an Artisan command using either the command's name or class:

    1. $schedule->command('emails:send --force')->daily();
    2. $schedule->command(EmailsCommand::class, ['--force'])->daily();

    Scheduling Queued Jobs

    The job method may be used to schedule a queued job. This method provides a convenient way to schedule jobs without using the call method to manually create Closures to queue the job:

    1. $schedule->job(new Heartbeat)->everyFiveMinutes();
    2. // Dispatch the job to the "heartbeats" queue...
    3. $schedule->job(new Heartbeat, 'heartbeats')->everyFiveMinutes();

    The exec method may be used to issue a command to the operating system:

    1. $schedule->exec('node /home/forge/script.js')->daily();

    Schedule Frequency Options

    These methods may be combined with additional constraints to create even more finely tuned schedules that only run on certain days of the week. For example, to schedule a command to run weekly on Monday:

    1. // Run once per week on Monday at 1 PM...
    2. $schedule->call(function () {
    3. //
    4. })->weekly()->mondays()->at('13:00');
    5. // Run hourly from 8 AM to 5 PM on weekdays...
    6. $schedule->command('foo')
    7. ->weekdays()
    8. ->timezone('America/Chicago')
    9. ->between('8:00', '17:00');

    Below is a list of the additional schedule constraints:

    MethodDescription
    ->weekdays();Limit the task to weekdays
    ->sundays();Limit the task to Sunday
    ->mondays();Limit the task to Monday
    ->tuesdays();Limit the task to Tuesday
    ->wednesdays();Limit the task to Wednesday
    ->thursdays();Limit the task to Thursday
    ->fridays();Limit the task to Friday
    ->saturdays();Limit the task to Saturday
    ->between($start, $end);Limit the task to run between start and end times
    ->when(Closure);Limit the task based on a truth test

    Between Time Constraints

    The between method may be used to limit the execution of a task based on the time of day:

    Similarly, the unlessBetween method can be used to exclude the execution of a task for a period of time:

    1. $schedule->command('reminders:send')
    2. ->hourly()
    3. ->unlessBetween('23:00', '4:00');

    Truth Test Constraints

    The when method may be used to limit the execution of a task based on the result of a given truth test. In other words, if the given Closure returns true, the task will execute as long as no other constraining conditions prevent the task from running:

    1. $schedule->command('emails:send')->daily()->when(function () {
    2. return true;
    3. });

    The skip method may be seen as the inverse of when. If the skip method returns true, the scheduled task will not be executed:

    1. $schedule->command('emails:send')->daily()->skip(function () {
    2. });

    When using chained when methods, the scheduled command will only execute if all when conditions return true.

    Timezones

    Using the timezone method, you may specify that a scheduled task's time should be interpreted within a given timezone:

    1. $schedule->command('report:generate')
    2. ->timezone('America/New_York')
    3. ->at('02:00')

    By default, scheduled tasks will be run even if the previous instance of the task is still running. To prevent this, you may use the withoutOverlapping method:

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

    In this example, the emails:send will be run every minute if it is not already running. The withoutOverlapping method is especially useful if you have tasks that vary drastically in their execution time, preventing you from predicting exactly how long a given task will take.

    If needed, you may specify how many minutes must pass before the "without overlapping" lock expires. By default, the lock will expire after 24 hours:

    1. $schedule->command('emails:send')->withoutOverlapping(10);

    Running Tasks On One Server

    If your application is running on multiple servers, you may limit a scheduled job to only execute on a single server. For instance, assume you have a scheduled task that generates a new report every Friday night. If the task scheduler is running on three worker servers, the scheduled task will run on all three servers and generate the report three times. Not good!

    To indicate that the task should run on only one server, use the onOneServer method when defining the scheduled task. The first server to obtain the task will secure an atomic lock on the job to prevent other servers from running the same task at the same time:

    Maintenance Mode

    Laravel's scheduled tasks will not run when Laravel is in , since we don't want your tasks to interfere with any unfinished maintenance you may be performing on your server. However, if you would like to force a task to run even in maintenance mode, you may use the evenInMaintenanceMode method:

    1. $schedule->command('emails:send')->evenInMaintenanceMode();

    The Laravel scheduler provides several convenient methods for working with the output generated by scheduled tasks. First, using the sendOutputTo method, you may send the output to a file for later inspection:

    1. $schedule->command('emails:send')
    2. ->daily()
    3. ->sendOutputTo($filePath);

    If you would like to append the output to a given file, you may use the appendOutputTo method:

    1. $schedule->command('emails:send')
    2. ->daily()
    3. ->appendOutputTo($filePath);

    Using the emailOutputTo method, you may e-mail the output to an e-mail address of your choice. Before e-mailing the output of a task, you should configure Laravel's :

    1. $schedule->command('foo')
    2. ->daily()
    3. ->sendOutputTo($filePath)
    4. ->emailOutputTo('[email protected]');

    Using the before and after methods, you may specify code to be executed before and after the scheduled task is complete:

    1. $schedule->command('emails:send')
    2. ->daily()
    3. ->before(function () {
    4. // Task is about to start...
    5. })
    6. ->after(function () {
    7. // Task is complete...
    8. });

    Pinging URLs

    Using the pingBefore and thenPing methods, the scheduler can automatically ping a given URL before or after a task is complete. This method is useful for notifying an external service, such as , that your scheduled task is commencing or has finished execution:

    1. $schedule->command('emails:send')
    2. ->daily()
    3. ->pingBefore($url)

    Using either the pingBefore($url) or feature requires the Guzzle HTTP library. You can add Guzzle to your project using the Composer package manager: