Skip to content

Advanced usage

Most projects create a handful of monitors with cron-monitor:create or the model. Large installations can keep the monitor definitions in a JSON file and sync them with one command.

Syncing monitors from a file

php artisan cron-monitor:sync-file monitors.json

The command reads a top-level JSON array. Each object is passed to fill() on a monitor found by hash. The command validates every cron_expression and the JSON structure before it writes or deletes anything. An invalid expression throws CannotSaveMonitor with the expression in the message.

Invalid JSON aborts the command with a non-zero exit code and a Could not parse ... as JSON error. Nothing is created, updated, or deleted, even with --delete-missing. A valid empty array ([]) is still an empty monitor list, so --delete-missing removes every monitor in that case. Check the file before you run the command in production.

[
  {
    "hash": "6f1c2f7a-0000-0000-0000-000000000000",
    "name": "Nightly invoice export",
    "description": "Exports paid invoices to the accounting system",
    "enabled": true,
    "cron_expression": "0 2 * * *",
    "timezone": "Europe/Vienna",
    "grace_period_in_minutes": 10
  },
  {
    "hash": "8a2d4b1c-0000-0000-0000-000000000000",
    "name": "Hourly stock sync",
    "enabled": true,
    "frequency_in_minutes": 60,
    "grace_period_in_minutes": 5,
    "timezone": "Europe/Vienna"
  }
]

hash is optional. When it is present, the command uses it to find an existing row and preserves it. When it is missing, the model generates a UUID for the new row.

Accepted fields

FieldTypeNotes
hashstringOptional. Used to find an existing row and preserved on insert. A missing value generates a UUID.
namestringDefaults to New CronMonitor on insert.
descriptionstring, null
enabledbooleanDefaults to true on insert.
statusstringOne of up, down, started, unknown.
cron_expressionstring, nullValidated with Cron\CronExpression::isValidExpression().
timezonestringDefaults to UTC on insert.
next_due_datedate string
frequency_in_minutesintegerDefaults to 60 on insert.
grace_period_in_minutesintegerDefaults to 5 on insert.
last_check_datedate string, null
last_check_failed_datedate string, null
status_last_change_datedate string
failure_reasonstring, null
last_ping_statusstringOne of success, error, started, unknown.

Do not send public. It is not a monitor attribute and the migration has no public column.

New rows and hashes

The command uses CronMonitor::firstOrNew(['hash' => ...]) when the entry has a hash. The model's creating hook only assigns a UUID when hash is empty, so a supplied hash is kept and the next run updates the same row. An entry without a hash is always inserted as a new row, because there is no hash to match. Add a hash to every entry when you want repeatable syncs.

The command writes the base JkOster\CronMonitor\Models\CronMonitor, not the model in monitor_model.

Deleting missing monitors

php artisan cron-monitor:sync-file monitors.json --delete-missing

Without the flag, rows that are not in the file stay untouched. With the flag, the command loads every row with CronMonitor::all() and deletes each one whose hash is not present in the file. Disabled rows are deleted too. There is no confirmation prompt. The command prints one line per deleted monitor. Invalid JSON stops the command before any row is deleted.

cron_monitors table

The published migration creates this table:

ColumnTypeDefaultNotes
idbigint unsignedauto increment
namevarcharNew CronMonitor
descriptionvarchar, nullablenull
enabledbooleantrueDisabled monitors are skipped by the health check.
hashvarchar, uniquenoneUUID assigned by the model.
statusvarcharunknownCronMonitorStatus value.
cron_expressionvarchar, nullablenullUsed after the first ping.
timezonevarcharUTCDatabase default. The model uses cron-monitor.timezone when the attribute is empty.
next_due_datetimestampnow()Computed from the schedule and grace period when not supplied explicitly. The health check marks the monitor down after this date.
frequency_in_minutesinteger60Used when no cron expression applies.
grace_period_in_minutesinteger5Window after a started ping.
last_check_datetimestamp, nullablenullUpdated by every accepted ping.
last_check_failed_datetimestamp, nullablenullSet when the monitor goes down.
status_last_change_datetimestampnow()Updated when status changes.
failure_reasontext, nullablenullBody or message from a failure ping, or the missed-check text.
last_ping_statusvarcharunknownIncomingPingStatus value.
created_at, updated_attimestamp, nullablenull

The migration file is database/migrations/create_cron_monitors_table.php.stub in the package. Publish it with php artisan vendor:publish --tag=migrations before migrating.

Custom notifications

The config maps notification classes to channels:

'notifications' => [
    App\Notifications\CronJobFailed::class => ['mail', 'slack'],
],

An empty array disables the notification. A custom class should extend the shipped notification for the event (CronCheckFailed or CronCheckRecovered), which already extends JkOster\CronMonitor\Notifications\BaseNotification. The handler maps the event to the shipped class, constructs it with the event data, and accepts a configured subclass in its place. The default classes are CronCheckFailed and CronCheckRecovered.

notifications.notifiable resolves the object that receives the notification. The default Notifiable reads the mail recipient and Slack webhook from the config. Replace it when you need a user model or a different routing rule.

The handler sends the shipped notifications for both events. A custom subclass only needs to override the message methods; the event-to-notification mapping and constructor arguments stay the same:

use JkOster\CronMonitor\Notifications\Notifications\CronCheckFailed;

class CronJobFailed extends CronCheckFailed
{
    protected function getMessageText(bool $withEmoji = true): string
    {
        return parent::getMessageText($withEmoji).' Please check the job.';
    }
}

Custom model

Set monitor_model to a class that extends JkOster\CronMonitor\Models\CronMonitor:

'monitor_model' => App\Models\CronMonitor::class,

CronMonitorRepository uses the configured class for every query. SyncFile does not; it uses the base model. If you rely on the sync command, keep the additional behavior in the base table or extend the command.

Protecting the ping routes

cron-monitor.api.middleware is applied to both ping routes and the status route. The routes are not in the web group, so there is no CSRF token check. They are not in the api group either, so there is no default throttling.

Add the middleware you need:

'api' => [
    'enabled' => true,
    'prefix' => 'cron-monitor',
    'middleware' => ['throttle:60,1'],
],

For authentication, add your guard, for example auth:sanctum, and send the token from the cron job. For a shared secret, write a small middleware that checks a header or a signature and add its class to the array.

The config is read when the service provider registers the routes. Run php artisan config:cache again after you change it.

Configuration

The published file is config/cron-monitor.php.

KeyDefaultNotes
timezoneenv('APP_TIMEZONE', 'UTC')Default for monitors created without a timezone and fallback for due-date calculations.
api.enabledtrueRegisters the ping and status routes.
api.prefixcron-monitorPath prefix for both routes.
api.middleware[]Middleware applied to both routes.
notifications.enabledtrueSubscribes the notification handler to the events.
notifications.notificationsCronCheckFailed and CronCheckRecovered, both ['slack', 'mail']Map of notification class to channels.
notifications.mail.to['your@email.com']Recipients for the mail channel.
notifications.slack.webhook_urlenv('CRON_MONITOR_SLACK_WEBHOOK_URL', '')Incoming webhook for the Slack channel.
notifications.notifiableJkOster\CronMonitor\Notifications\NotifiableObject that receives the notification.
notifications.date_formatd/m/YDate format in notification text.
monitor_modelJkOster\CronMonitor\Models\CronMonitorMust extend the base model.

BaseNotification also reads notifications.location, but the published config does not define it. Leave it out unless you add it yourself.