GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — docs/scheduling.md at 0.4 · hypervel/docs

Expand file tree

/

scheduling.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
801 lines (581 loc) · 35.3 KB
/

scheduling.md

Copy path

File metadata and controls

801 lines (581 loc) · 35.3 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

Task Scheduling

  • Introduction
  • Defining Schedules
    • Scheduling Artisan Commands
    • Scheduling Queued Jobs
    • Scheduling Shell Commands
    • Schedule Frequency Options
    • Timezones
    • Preventing Task Overlaps
    • Running Tasks on One Server
    • Background Tasks
    • Maintenance Mode
    • Pausing Scheduled Tasks
    • Schedule Groups
  • Running the Scheduler
    • Cron-Style Invocation
    • Background Task Concurrency
    • Sub-Minute Scheduled Tasks
    • Stopping the Scheduler
    • Running the Scheduler Locally
    • Testing Scheduled Tasks
  • Task Output
  • Task Hooks
  • Events

Introduction

In the past, you may have written a cron configuration 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 view your existing cron entries or add additional entries.

Hypervel's command scheduler offers a fresh approach to managing scheduled tasks on your server. The scheduler allows you to fluently and expressively define your command schedule within your Hypervel application itself. When using the scheduler, only a single long-running scheduler process is needed on your server. Your task schedule is typically defined in your application's routes/console.php file.

Defining Schedules

You may define all of your scheduled tasks in your application's routes/console.php file. To get started, let's take a look at an example. 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:

<?php

use Hypervel\Support\Facades\DB;
use Hypervel\Support\Facades\Schedule;

Schedule::call(function () {
    DB::table('recent_users')->delete();
})->daily();

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

Schedule::call(new DeleteRecentUsers)->daily();

If you prefer to reserve your routes/console.php file for command definitions only, you may use the withSchedule method in your application's bootstrap/app.php file to define your scheduled tasks. This method accepts a closure that receives an instance of the scheduler:

use Hypervel\Console\Scheduling\Schedule;

->withSchedule(function (Schedule $schedule) {
    $schedule->call(new DeleteRecentUsers)->daily();
})

If you would like to view an overview of your scheduled tasks and the next time they are scheduled to run, you may use the schedule:list Artisan command:

php artisan schedule:list

The schedule:list command also supports --timezone, --environment, --next, and --json options for customizing the displayed timezone, filtering by environment, sorting by the next due date, or returning the schedule as JSON. JSON output includes an on_one_server field indicating whether each task is configured to run on one server. The --environment option may be repeated to include tasks from multiple environments:

php artisan schedule:list --environment=staging --environment=production

Scheduling Artisan Commands

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

When scheduling Artisan commands using the command's class name, you may pass an array of additional command-line arguments that should be provided to the command when it is invoked:

use App\Console\Commands\SendEmailsCommand;
use Hypervel\Support\Facades\Schedule;

Schedule::command('emails:send Taylor --force')->daily();

Schedule::command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();

Scheduled commands and closures run within the scheduler process, so static and singleton state persists between tasks. If a command needs a separate process, schedule it with Schedule::exec('php artisan emails:send Taylor --force') instead.

Scheduling Artisan Closure Commands

If you want to schedule an Artisan command defined by a closure, you may chain the scheduling related methods after the command's definition:

Artisan::command('delete:recent-users', function () {
    DB::table('recent_users')->delete();
})->purpose('Delete recent users')->daily();

If you need to pass arguments to the closure command, you may provide them to the schedule method:

Artisan::command('emails:send {user} {--force}', function ($user) {
    // ...
})->purpose('Send emails to the specified user')->schedule(['Taylor', '--force'])->daily();

Scheduling Queued Jobs

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

use App\Jobs\Heartbeat;
use Hypervel\Support\Facades\Schedule;

Schedule::job(new Heartbeat)->everyFiveMinutes();

Optional second and third arguments may be provided to the job method which specifies the queue name and queue connection that should be used to queue the job:

use App\Jobs\Heartbeat;
use Hypervel\Support\Facades\Schedule;

// Dispatch the job to the "heartbeats" queue on the "sqs" connection...
Schedule::job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes();

When you pass a job class string, Hypervel resolves it through the container for every due firing. Explicit container lifetimes remain authoritative, so a job registered as a singleton is dispatched as that same instance on every firing.

Scheduling Shell Commands

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

use Hypervel\Support\Facades\Schedule;

Schedule::exec('node /path/to/script.js')->daily();

If the shell command launches a Hypervel Artisan command, the child command receives the task's visible and hidden context.

Scheduled tasks run as the scheduler's OS user. To run a task as another user, use exec with an explicit command, such as sudo -u reports -- /usr/local/bin/generate-reports.

Schedule Frequency Options

We've already seen a few examples of how you may configure a task to run at specified intervals. However, there are many more task schedule frequencies that you may assign to a task:

Method Description
->cron('* * * * *'); Run the task on a custom cron schedule.
->everySecond(); Run the task every second.
->everyTwoSeconds(); Run the task every two seconds.
->everyFiveSeconds(); Run the task every five seconds.
->everyTenSeconds(); Run the task every ten seconds.
->everyFifteenSeconds(); Run the task every fifteen seconds.
->everyTwentySeconds(); Run the task every twenty seconds.
->everyThirtySeconds(); Run the task every thirty seconds.
->everyMinute(); Run the task every minute.
->everyTwoMinutes(); Run the task every two minutes.
->everyThreeMinutes(); Run the task every three minutes.
->everyFourMinutes(); Run the task every four minutes.
->everyFiveMinutes(); Run the task every five minutes.
->everyTenMinutes(); Run the task every ten minutes.
->everyFifteenMinutes(); Run the task every fifteen minutes.
->everyThirtyMinutes(); Run the task every thirty minutes.
->hourly(); Run the task every hour.
->hourlyAt(17); Run the task every hour at 17 minutes past the hour.
->everyOddHour($minutes = 0); Run the task every odd hour.
->everyTwoHours($minutes = 0); Run the task every two hours.
->everyThreeHours($minutes = 0); Run the task every three hours.
->everyFourHours($minutes = 0); Run the task every four hours.
->everySixHours($minutes = 0); Run the task every six hours.
->daily(); Run the task every day at midnight.
->dailyAt('13:00'); Run the task every day at 13:00.
->twiceDaily(1, 13); Run the task daily at 1:00 & 13:00.
->twiceDailyAt(1, 13, 15); Run the task daily at 1:15 & 13:15.
->daysOfMonth([1, 10, 20]); Run the task on specific days of the month.
->weekly(); Run the task every Sunday at 00:00.
->weeklyOn(1, '8:00'); Run the task every week on Monday at 8:00.
->monthly(); Run the task on the first day of every month at 00:00.
->monthlyOn(4, '15:00'); Run the task every month on the 4th at 15:00.
->twiceMonthly(1, 16, '13:00'); Run the task monthly on the 1st and 16th at 13:00.
->lastDayOfMonth('15:00'); Run the task on the last day of the month at 15:00.
->quarterly(); Run the task on the first day of every quarter at 00:00.
->quarterlyOn(4, '14:00'); Run the task every quarter on the 4th at 14:00.
->yearly(); Run the task on the first day of every year at 00:00.
->yearlyOn(6, 1, '17:00'); Run the task every year on June 1st at 17:00.
->timezone('America/New_York'); Set the timezone for the task.

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, you may schedule a command to run weekly on Monday:

use Hypervel\Support\Facades\Schedule;

// Run once per week on Monday at 1 PM...
Schedule::call(function () {
    // ...
})->weekly()->mondays()->at('13:00');

// Run hourly from 8 AM to 5 PM on weekdays...
Schedule::command('foo')
    ->weekdays()
    ->hourly()
    ->timezone('America/Chicago')
    ->between('8:00', '17:00');

A list of additional schedule constraints may be found below:

Method Description
->weekdays(); Limit the task to weekdays.
->weekends(); Limit the task to weekends.
->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.
->days(array|mixed); Limit the task to specific days.
->between($startTime, $endTime); Limit the task to run between start and end times.
->unlessBetween($startTime, $endTime); Limit the task to not run between start and end times.
->when(Closure); Limit the task based on a truth test.
->environments($env); Limit the task to specific environments.

Day Constraints

The days method may be used to limit the execution of a task to specific days of the week. For example, you may schedule a command to run hourly on Sundays and Wednesdays:

use Hypervel\Support\Facades\Schedule;

Schedule::command('emails:send')
    ->hourly()
    ->days([0, 3]);

Alternatively, you may use the constants available on the Hypervel\Console\Scheduling\Schedule class when defining the days on which a task should run:

use Hypervel\Support\Facades;
use Hypervel\Console\Scheduling\Schedule;

Facades\Schedule::command('emails:send')
    ->hourly()
    ->days([Schedule::SUNDAY, Schedule::WEDNESDAY]);

Between Time Constraints

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

Schedule::command('emails:send')
    ->hourly()
    ->between('7:00', '22:00');

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

Schedule::command('emails:send')
    ->hourly()
    ->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:

Schedule::command('emails:send')->daily()->when(function () {
    return true;
});

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

Schedule::command('emails:send')->daily()->skip(function () {
    return true;
});

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

Environment Constraints

The environments method may be used to execute tasks only on the given environments (as defined by the APP_ENV environment variable):

Schedule::command('emails:send')
    ->daily()
    ->environments(['staging', 'production']);

Timezones

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

use Hypervel\Support\Facades\Schedule;

Schedule::command('report:generate')
    ->timezone('America/New_York')
    ->at('2:00');

If you are repeatedly assigning the same timezone to all of your scheduled tasks, you can specify which timezone should be assigned to all schedules by defining a schedule_timezone option within your application's app configuration file:

'timezone' => 'UTC',

'schedule_timezone' => 'America/Chicago',

When this option is omitted, scheduled tasks use the application timezone.

Warning

Remember that some timezones utilize daylight saving time. When daylight saving time changes occur, your scheduled task may run twice or even not run at all. For this reason, we recommend avoiding timezone scheduling when possible.

When using schedule:list --timezone, the next due date is displayed in the requested timezone while the cron expression remains in the timezone in which it is evaluated. If these timezones differ, the CLI displays the expression timezone beside the expression. JSON output provides the display timezone as timezone and the expression timezone as expression_timezone.

Preventing Task Overlaps

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:

use Hypervel\Support\Facades\Schedule;

Schedule::command('emails:send')->withoutOverlapping();

In this example, the emails:send Artisan command 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:

Schedule::command('emails:send')->withoutOverlapping(10);

Behind the scenes, the withoutOverlapping method utilizes your application's cache to obtain locks. If necessary, you can clear these cache locks using the schedule:clear-cache Artisan command. This is typically only necessary if a task becomes stuck due to an unexpected server problem.

By default, scheduling locks use the cache store configured by the cache.schedule_store option. This option reads the SCHEDULE_CACHE_STORE environment variable and may be set to null to use your application's default cache store:

SCHEDULE_CACHE_STORE=database

Running Tasks on One Server

Warning

To utilize this feature across multiple servers, your application should use a shared database or redis cache store for scheduling locks. In addition, all servers must be communicating with the same central cache store.

If your application's scheduler 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:

use Hypervel\Support\Facades\Schedule;

Schedule::command('report:generate')
    ->fridays()
    ->at('17:00')
    ->onOneServer();

To apply onOneServer to all scheduled tasks, you may call the alwaysOnOneServer method in the boot method of your application's AppServiceProvider:

use Hypervel\Console\Scheduling\Schedule;

public function boot(): void
{
    Schedule::alwaysOnOneServer();
}

Scheduled callbacks without a name, including closures and invokable objects, are excluded and will continue to run on every server.

You may use the useCache method to override the configured cache store used by the scheduler to obtain the atomic locks necessary for single-server tasks:

Schedule::useCache('database');

Naming Single Server Jobs

Sometimes you may need to schedule the same job to be dispatched with different parameters, while still instructing Hypervel to run each permutation of the job on a single server. To accomplish this, you may assign each schedule definition a unique name via the name method:

Schedule::job(new CheckUptime('https://hypervel.org'))
    ->name('check_uptime:hypervel.org')
    ->everyFiveMinutes()
    ->onOneServer();

Schedule::job(new CheckUptime('https://sonicstack.io'))
    ->name('check_uptime:sonicstack.io')
    ->everyFiveMinutes()
    ->onOneServer();

Similarly, scheduled closures must be assigned a name if they are intended to be run on one server:

Schedule::call(fn () => User::resetApiRequestCount())
    ->name('reset-api-request-count')
    ->daily()
    ->onOneServer();

Background Tasks

By default, multiple tasks scheduled at the same time will execute sequentially based on the order they are defined in your schedule method. If you have long-running tasks, this may cause subsequent tasks to start much later than anticipated. If you would like to run tasks in the background so that they may all run simultaneously, you may use the runInBackground method:

use Hypervel\Support\Facades\Schedule;

Schedule::command('analytics:report')
    ->daily()
    ->runInBackground();

Warning

The runInBackground method may only be used when scheduling tasks via the command and exec methods.

Hypervel starts background tasks as coroutines inside the schedule:run process. This is well suited to I/O-bound work such as HTTP calls, queries, and file or network I/O because coroutines yield while waiting. For CPU-bound work, coroutines offer limited benefit. In those cases, schedule the task using exec so the operating system runs it in a separate process:

Schedule::exec('php artisan reports:compute')
    ->daily()
    ->runInBackground();

Unlike Laravel's detached background processes, Hypervel observes the exit status of background tasks. A non-zero exit dispatches a ScheduledTaskFailed event and is reported through the exception handler.

Maintenance Mode

Your application's scheduled tasks will not run when the application is in maintenance mode, 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 call the evenInMaintenanceMode method when defining the task:

Schedule::command('emails:send')->evenInMaintenanceMode();

Pausing Scheduled Tasks

You may temporarily pause scheduled task processing without changing your deployed code by using the schedule:pause Artisan command:

php artisan schedule:pause

While the scheduler is paused, no scheduled tasks will run. You may resume scheduled task processing using the schedule:resume command:

php artisan schedule:resume

The schedule:continue command is also available as an alias for schedule:resume.

If a task should still run while the scheduler is paused, you may mark it with the evenWhenPaused method:

Schedule::command('emails:send')->evenWhenPaused();

Schedule Groups

When defining multiple scheduled tasks with similar configurations, you can use Hypervel's task grouping feature to avoid repeating the same settings for each task. Grouping tasks simplifies your code and ensures consistency across related tasks.

To create a group of scheduled tasks, invoke the desired task configuration methods, followed by the group method. The group method accepts a closure that is responsible for defining the tasks that share the specified configuration:

use Hypervel\Support\Facades\Schedule;

Schedule::daily()
    ->onOneServer()
    ->timezone('America/New_York')
    ->withAttributes(['team' => 'mail'])
    ->group(function () {
        Schedule::command('emails:send --force');
        Schedule::command('emails:prune');
    });

You may also apply event callbacks, output handlers, and event macros to every task in a group. These methods may appear before or after the group's frequency settings:

Schedule::daily()
    ->after(function () {
        // ...
    })
    ->group(function () {
        Schedule::command('reports:send');
        Schedule::command('reports:prune');
    });

Running the Scheduler

Now that we have learned how to define scheduled tasks, let's discuss how to actually run them on our server. Hypervel's schedule:run Artisan command is a long-running coroutine-based process by default. It evaluates all due events, dispatches background tasks in coroutines, and continues polling for upcoming tasks.

You should run this command as a supervised process using a process monitor such as systemd, Supervisor, or your container orchestrator:

php artisan schedule:run

If you do not know how to manage long-running PHP processes on your server, consider using SonicStack which can manage the scheduled task execution for you. Using SonicStack is also a great way to support ongoing Hypervel development.

Cron-Style Invocation

If you prefer to invoke the scheduler from a traditional cron entry, pass the --once option so the scheduler evaluates due events and exits immediately:

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

Background Task Concurrency

The --concurrency option controls how many runInBackground tasks may execute simultaneously as coroutines. By default, Hypervel allows 60 background tasks to run at the same time:

php artisan schedule:run --concurrency=100

Sub-Minute Scheduled Tasks

On most operating systems, cron jobs are limited to running a maximum of once per minute. However, Hypervel's scheduler allows you to schedule tasks to run at more frequent intervals, even as often as once per second:

use Hypervel\Support\Facades\Schedule;

Schedule::call(function () {
    DB::table('recent_users')->delete();
})->everySecond();

Because schedule:run is a long-running process, sub-minute tasks fire as soon as they become due without any additional configuration.

Since sub-minute tasks that take longer than expected to run could delay the execution of later sub-minute tasks, it is recommended that all sub-minute tasks dispatch queued jobs or background commands to handle the actual task processing:

use App\Jobs\DeleteRecentUsers;

Schedule::job(new DeleteRecentUsers)->everyTenSeconds();

Schedule::command('users:delete')->everyTenSeconds()->runInBackground();

Stopping the Scheduler

When the long-running schedule:run process receives SIGTERM, SIGINT, or SIGQUIT, it stops starting new tasks and waits for running tasks to finish. A second termination signal stops the process immediately and releases its owned overlap locks, unless the task disables releaseOnTerminationSignals. Configure your process manager's shutdown timeout to allow your longest task to finish. A forced SIGKILL cannot release overlap locks; they remain until they expire or you run schedule:clear-cache.

When deploying your application, you may also use schedule:interrupt to stop the scheduler so that the next invocation picks up your newly deployed code. This command records an interruption timestamp in the cache. Schedulers started before the interruption finish the current set of due events and wait for running background tasks before exiting. Schedulers started afterward are unaffected.

This command should be invoked after your application is finished deploying:

php artisan schedule:interrupt

Long-running scheduled commands may check for an interruption between units of work using Schedule::hasBeenInterruptedSince. Record the command's start time and pass it to this method:

use Hypervel\Support\Facades\Schedule;

$startedAt = now();

foreach ($items as $item) {
    if (Schedule::hasBeenInterruptedSince($startedAt)) {
        break;
    }

    // Process the item...
}

If you do not want the scheduler to poll for pause or interrupt signals, call Schedule::withoutInterruptionPolling() during boot. The schedule:pause command will then fail instead of pausing the scheduler, and Schedule::hasBeenInterruptedSince will return false. Operating-system termination signals still stop the scheduler.

Running the Scheduler Locally

No separate local development command is needed. The schedule:run command runs in the foreground as a long-running process. Press Control+C to stop after running tasks finish, or press it again to stop immediately:

php artisan schedule:run

Testing Scheduled Tasks

If you would like to run one of your scheduled tasks immediately, you may use the schedule:test Artisan command:

php artisan schedule:test

If your application has multiple scheduled tasks, Hypervel will prompt you to choose the task that should be executed. You may also pass the --name option to run a specific scheduled task by name.

Task Output

The Hypervel 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:

use Hypervel\Support\Facades\Schedule;

Schedule::command('emails:send')
    ->daily()
    ->sendOutputTo($filePath);

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

Schedule::command('emails:send')
    ->daily()
    ->appendOutputTo($filePath);

Using the emailOutputTo method, you may email the output to an email address of your choice. Before emailing the output of a task, you should configure Hypervel's email services:

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

If you only want to email the output if the scheduled Artisan or system command terminates with a non-zero exit code, use the emailOutputOnFailure method:

Schedule::command('report:generate')
    ->daily()
    ->emailOutputOnFailure('[email protected]');

Warning

The emailOutputTo, emailOutputOnFailure, sendOutputTo, and appendOutputTo methods are exclusive to the command and exec methods.

Task Hooks

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

use Hypervel\Support\Facades\Schedule;

Schedule::command('emails:send')
    ->daily()
    ->before(function () {
        // The task is about to execute...
    })
    ->after(function () {
        // The task has executed...
    });

Scheduled task constraint and lifecycle callbacks are invoked through the service container, so you may type-hint dependencies. You may also type-hint Hypervel\Console\Scheduling\Event to receive the current scheduled event:

use App\Services\Metrics;
use Hypervel\Console\Scheduling\Event;

Schedule::command('emails:send')
    ->daily()
    ->before(function (Event $event, Metrics $metrics) {
        $metrics->recordStarting($event);
    });

The onSuccess and onFailure methods allow you to specify code to be executed if the scheduled task succeeds or fails. A failure indicates that the scheduled Artisan or system command terminated with a non-zero exit code:

Schedule::command('emails:send')
    ->daily()
    ->onSuccess(function () {
        // The task succeeded...
    })
    ->onFailure(function () {
        // The task failed...
    });

If output is available from your command, you may access it in your after, onSuccess or onFailure hooks by type-hinting a Hypervel\Support\Stringable instance as the $output argument of your hook's closure definition:

use Hypervel\Support\Stringable;

Schedule::command('emails:send')
    ->daily()
    ->onSuccess(function (Stringable $output) {
        // The task succeeded...
    })
    ->onFailure(function (Stringable $output) {
        // The task failed...
    });

Pinging URLs

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

Schedule::command('emails:send')
    ->daily()
    ->pingBefore($url)
    ->thenPing($url);

The pingOnSuccess and pingOnFailure methods may be used to ping a given URL only if the task succeeds or fails. A failure indicates that the scheduled Artisan or system command terminated with a non-zero exit code:

Schedule::command('emails:send')
    ->daily()
    ->pingOnSuccess($successUrl)
    ->pingOnFailure($failureUrl);

The pingBeforeIf,thenPingIf,pingOnSuccessIf, and pingOnFailureIf methods may be used to ping a given URL only if a given condition is true:

Schedule::command('emails:send')
    ->daily()
    ->pingBeforeIf($condition, $url)
    ->thenPingIf($condition, $url);

Schedule::command('emails:send')
    ->daily()
    ->pingOnSuccessIf($condition, $successUrl)
    ->pingOnFailureIf($condition, $failureUrl);

Events

Hypervel dispatches a variety of events during the scheduling process. You may define listeners for any of the following events:

Event Name
Hypervel\Console\Events\ScheduledTaskStarting
Hypervel\Console\Events\ScheduledTaskFinished
Hypervel\Console\Events\ScheduledBackgroundTaskFinished
Hypervel\Console\Events\ScheduledTaskSkipped
Hypervel\Console\Events\ScheduledTaskFailed

The ScheduledTaskFailed event's runtime property contains the elapsed execution time in seconds, or null when the runtime is unavailable.

If you would like to be notified when a scheduled task takes too long to run, you may use the whenTaskRunsLongerThan method in your application's routes/console.php file. Provide a threshold in seconds, or a CarbonInterval, and a closure that receives the task and the number of seconds it ran. The closure is invoked once for each run that exceeds the threshold, including runs that fail:

use Hypervel\Console\Scheduling\Event;
use Hypervel\Support\Facades\Schedule;

Schedule::whenTaskRunsLongerThan(60, function (Event $task, float $runtime) {
    // Notify the development team...
});
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.