定制 spatie/laravel-schedule-monitor 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

spatie/laravel-schedule-monitor

Composer 安装命令:

composer require spatie/laravel-schedule-monitor

包简介

Monitor scheduled tasks in a Laravel app

README 文档

README

Latest Version on Packagist Total Downloads

This package will monitor your Laravel schedule. It will write an entry to a log table in the db each time a schedule tasks starts, end, fails or is skipped. Using the list command you can check when the scheduled tasks have been executed.

screenshot

This package can also sync your schedule with Oh Dear. Oh Dear will send you a notification whenever a scheduled task doesn't run on time or fails.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-schedule-monitor

If you need Laravel 8 support, you can install v2 of the package using composer require spatie/laravel-schedule-monitor:^2.

Preparing the database

You must publish and run migrations:

php artisan vendor:publish --provider="Spatie\ScheduleMonitor\ScheduleMonitorServiceProvider" --tag="schedule-monitor-migrations"
php artisan migrate

Publishing the config file

You can publish the config file with:

php artisan vendor:publish --provider="Spatie\ScheduleMonitor\ScheduleMonitorServiceProvider" --tag="schedule-monitor-config"

This is the contents of the published config file:

return [
    /*
     * The schedule monitor will log each start, finish and failure of all scheduled jobs.
     * After a while the `monitored_scheduled_task_log_items` might become big.
     * Here you can specify the amount of days log items should be kept.
     *
     * Use Laravel's pruning command to delete old `MonitoredScheduledTaskLogItem` models.
     * More info: https://laravel.com/docs/11.x/eloquent#pruning-models
     */
    'delete_log_items_older_than_days' => 30,

    /*
     * The date format used for all dates displayed on the output of commands
     * provided by this package.
     */
    'date_format' => 'Y-m-d H:i:s',

    'models' => [
        /*
         * The model you want to use as a MonitoredScheduledTask model needs to extend the
         * `Spatie\ScheduleMonitor\Models\MonitoredScheduledTask` Model.
         */
        'monitored_scheduled_task' => Spatie\ScheduleMonitor\Models\MonitoredScheduledTask::class,

        /*
         * The model you want to use as a MonitoredScheduledTaskLogItem model needs to extend the
         * `Spatie\ScheduleMonitor\Models\MonitoredScheduledTaskLogItem` Model.
         */
        'monitored_scheduled_log_item' => Spatie\ScheduleMonitor\Models\MonitoredScheduledTaskLogItem::class,
    ],

    /*
     * Oh Dear can notify you via Mail, Slack, SMS, web hooks, ... when a
     * scheduled task does not run on time.
     *
     * More info: https://ohdear.app/docs/features/cron-job-monitoring
     */
    'oh_dear' => [
        /*
         * You can generate an API token at the Oh Dear user settings screen
         *
         * https://ohdear.app/user/api-tokens
         */
        'api_token' => env('OH_DEAR_API_TOKEN', ''),

        /*
         *  The id of the monitor you want to sync the schedule with.
         *
         * You'll find this id on the settings page of a monitor at Oh Dear.
         */
        'monitor_id' => env('OH_DEAR_MONITOR_ID'),

        /*
         * To keep scheduled jobs as short as possible, Oh Dear will be pinged
         * via a queued job. Here you can specify the name of the queue you wish to use.
         */
        'queue' => env('OH_DEAR_QUEUE'),

        /*
         * The job class that will be dispatched to ping Oh Dear.
         */
        'ping_oh_dear_job' => Spatie\ScheduleMonitor\Jobs\PingOhDearJob::class,

        /*
         * `PingOhDearJob`s will automatically be skipped if they've been queued for
         * longer than the time configured here.
         */
        'retry_job_for_minutes' => 10,

        /*
         * When set to true, we will automatically add the `PingOhDearJob` to Horizon's
         * silenced jobs.
         */
        'silence_ping_oh_dear_job_in_horizon' => true,

        /*
         * Send the start of a scheduled job to Oh Dear. This is not needed
         * for notifications to work correctly.
         */
        'send_starting_ping' => env('OH_DEAR_SEND_STARTING_PING', false),

        /**
         * The amount of minutes a scheduled task is allowed to run before it is
         * considered late.
         */
        'grace_time_in_minutes' => 5,

        /**
         * Which endpoint to ping on Oh Dear.
         */
        'endpoint_url' => env('OH_DEAR_PING_ENDPOINT_URL'),

        /**
         * The URL of the Oh Dear API.
         */
        'api_url' => env('OH_DEAR_API_URL', 'https://ohdear.app/api/'),

        /*
         * The delay in milliseconds between retry attempts when a ping fails.
         */
        'retry_delay_ms' => env('OH_DEAR_RETRY_DELAY_MS', 10_000),

        /*
         * When enabled, failed pings to Oh Dear will log detailed diagnostics
         * including request timing, connection info, and response data.
         * Useful for debugging connectivity issues with ping.ohdear.app.
         */
        'debug_logging' => env('OH_DEAR_DEBUG_LOGGING', false),
    ],
];

Debugging failed pings

If you're experiencing intermittent timeouts or connection issues when pinging Oh Dear, you can enable debug logging to get detailed diagnostics on every failed ping:

OH_DEAR_DEBUG_LOGGING=true

When enabled, each failed ping will write a Log::warning with the full request details, cURL timing breakdown (DNS lookup, TCP connect, TLS handshake, time-to-first-byte), connection info (resolved IP, local IP), and the server response if one was received.

Cleaning the database

The schedule monitor will log each start, finish and failure of all scheduled jobs. After a while the monitored_scheduled_task_log_items might become big.

Use Laravel's model pruning feature , you can delete old MonitoredScheduledTaskLogItem models. Models older than the amount of days configured in the delete_log_items_older_than_days in the schedule-monitor config file, will be deleted.

// app/Console/Kernel.php

use Spatie\ScheduleMonitor\Models\MonitoredScheduledTaskLogItem;

class Kernel extends ConsoleKernel
{
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('model:prune', ['--model' => MonitoredScheduledTaskLogItem::class])->daily();
    }
}

Syncing the schedule

Every time you deploy your application, you should execute the schedule-monitor:sync command

php artisan schedule-monitor:sync

This command is responsible for syncing your schedule with the database, and optionally Oh Dear. We highly recommend adding this command to the script that deploys your production environment.

In a non-production environment you should manually run schedule-monitor:sync. You can verify if everything synced correctly using schedule-monitor:list.

Note: Running the sync command will remove any other cron monitors that you've defined other than the application schedule.

If you would like to use non-destructive syncs to Oh Dear so that you can monitor other cron tasks outside of Laravel, you can use the --keep-old flag. This will only push new tasks to Oh Dear, rather than a full sync. Note that this will not remove any tasks from Oh Dear that are no longer in your schedule.

Usage

To monitor your schedule you should first run schedule-monitor:sync. This command will take a look at your schedule and create an entry for each task in the monitored_scheduled_tasks table.

screenshot

To view all monitored scheduled tasks, you can run schedule-monitor:list. This command will list all monitored scheduled tasks. It will show you when a scheduled task has last started, finished, or failed.

screenshot

The package will write an entry to the monitored_scheduled_task_log_items table in the db each time a schedule tasks starts, end, fails or is skipped. Take a look at the contents of that table if you want to know when and how scheduled tasks did execute. The log items also hold other interesting metrics like memory usage, execution time, and more.

Naming tasks

Schedule monitor will try to automatically determine a name for a scheduled task. For commands this is the command name, for anonymous jobs the class name of the first argument will be used. For some tasks, like scheduled closures, a name cannot be determined automatically.

To manually set a name of the scheduled task, you can tack on monitorName().

Here's an example.

// in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
   $schedule->command('your-command')->daily()->monitorName('a-custom-name');
   $schedule->call(fn () => 1 + 1)->hourly()->monitorName('addition-closure');
}

When you change the name of task, the schedule monitor will remove all log items of the monitor with the old name, and create a new monitor using the new name of the task.

Setting a grace time

When the package detects that the last run of a scheduled task did not run in time, the schedule-monitor list will display that task using a red background color. In this screenshot the task named your-command ran too late.

screenshot

The package will determine that a task ran too late if it was not finished at the time it was supposed to run + the grace time. You can think of the grace time as the number of minutes that a task under normal circumstances needs to finish. By default, the package grants a grace time of 5 minutes to each task.

You can customize the grace time by using the graceTimeInMinutes method on a task. In this example a grace time of 10 minutes is used for the your-command task.

// in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
   $schedule->command('your-command')->daily()->graceTimeInMinutes(10);
}

Ignoring scheduled tasks

You can avoid a scheduled task being monitored by tacking on doNotMonitor when scheduling the task.

// in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
   $schedule->command('your-command')->daily()->doNotMonitor();
}

Storing output in the database

You can store the output by tacking on storeOutputInDb when scheduling the task.

// in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
   $schedule->command('your-command')->daily()->storeOutputInDb();
}

The output will be stored in the monitored_scheduled_task_log_items table, in the output key of the meta column.

Multitenancy

If you're using spatie/laravel-multitenancy you should add the PingOhDearJob to the not_tenant_aware_jobs array in config/multitenancy.php.

'not_tenant_aware_jobs' => [
    // ...
    \Spatie\ScheduleMonitor\Jobs\PingOhDearJob::class,
]

Without it, the PingOhDearJob will fail as no tenant will be set.

Getting notified when a scheduled task doesn't finish in time

This package can sync your schedule with the Oh Dear cron check. Oh Dear will send you a notification whenever a scheduled task does not finish on time.

You eed to make sure the api_token and monitor_id keys of the schedule-monitor are filled with an API token, and an Oh Dear monitor id. To verify that these values hold correct values you can run this command.

php artisan schedule-monitor:verify

screenshot

To sync your schedule with Oh Dear run this command:

php artisan schedule-monitor:sync

screenshot

After that, the list command should show that all the scheduled tasks in your app are registered on Oh Dear.

screenshot

To keep scheduled jobs as short as possible, Oh Dear will be pinged via queued jobs. To ensure speedy delivery to Oh Dear, and to avoid false positive notifications, we highly recommend creating a dedicated queue for these jobs. You can put the name of that queue in the queue key of the config file.

Oh Dear will wait for the completion of a schedule tasks for a given amount of minutes. This is called the grace time. By default, all scheduled tasks will have a grace time of 5 minutes. To customize this value, you can tack on graceTimeInMinutes to your scheduled tasks.

Here's an example where Oh Dear will send a notification if the task didn't finish by 00:10.

// in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
   $schedule->command('your-command')->daily()->graceTimeInMinutes(10);
}

Disabling Oh Dear for individual tasks

If you want to have a task monitored by the schedule monitor, but not by Oh Dear, you can tack on doMonitorAtOhDear to your scheduled tasks.

// in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
   $schedule->command('your-command')->daily()->doNotMonitorAtOhDear();
}

Customizing the Oh Dear ping job

By default, the package dispatches Spatie\ScheduleMonitor\Jobs\PingOhDearJob to send pings to Oh Dear. You can customize this job class.

To use a custom job class, update the ping_oh_dear_job configuration in your config/schedule-monitor.php file:

'oh_dear' => [
    // ...
    'ping_oh_dear_job' => \App\Jobs\CustomPingOhDearJob::class,
],

Do make sure your custom job class extends Spatie\ScheduleMonitor\Jobs\PingOhDearJob to retain the original functionality. Here's an example of a custom job class:

namespace App\Jobs;

use Spatie\ScheduleMonitor\Jobs\PingOhDearJob;
use Spatie\ScheduleMonitor\Models\MonitoredScheduledTaskLogItem;

class CustomPingOhDearJob extends PingOhDearJob
{
    // your implementation
}

Unsupported methods

Currently, this package does not work for tasks that use these methods:

  • between
  • unlessBetween
  • when
  • skip

Third party scheduled task monitors

We assume that, when your scheduled tasks do not run properly, a scheduled task that sends out notifications would probably not run either. That's why this package doesn't send out notifications by itself.

These services can notify you when scheduled tasks do not run properly:

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

spatie/laravel-schedule-monitor 适用场景与选型建议

spatie/laravel-schedule-monitor 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.44M 次下载、GitHub Stars 达 993, 最近一次更新时间为 2020 年 07 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「spatie」 「laravel-schedule-monitor」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 spatie/laravel-schedule-monitor 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 spatie/laravel-schedule-monitor 我们能提供哪些服务?
定制开发 / 二次开发

基于 spatie/laravel-schedule-monitor 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.44M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 999
  • 点击次数: 17
  • 依赖项目数: 12
  • 推荐数: 0

GitHub 信息

  • Stars: 993
  • Watchers: 6
  • Forks: 73
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-07-08