Database and Models

laravel-schedule-monitor stores its data in two tables, accessed through two Eloquent models. This page documents the schema, the models' public methods, how to query the history, how to replace the models with your own, and how pruning works.

Database Schema

monitored_scheduled_tasks

One row per monitored task, created and updated by schedule-monitor:sync.

Column Type Description
id big increments
name string The task name, the lookup key. Not declared unique in the migration; the sync keeps it unique.
type string, nullable command, job, closure, or shell
cron_expression string The task's cron expression
timezone string, nullable The task's timezone
ping_url string, nullable The Oh Dear ping URL; null when the task is not monitored at Oh Dear
last_started_at datetime, nullable Time of the last starting event
last_finished_at datetime, nullable Time of the last successful finish
last_failed_at datetime, nullable Time of the last failure
last_skipped_at datetime, nullable Time of the last skip
registered_on_oh_dear_at datetime, nullable When the task was first registered at Oh Dear
last_pinged_at datetime, nullable Time of the last successful ping to Oh Dear
grace_time_in_minutes integer The task's grace time
created_at, updated_at timestamps

monitored_scheduled_task_log_items

One row per scheduler event of a monitored task.

Column Type Description
id big increments
monitored_scheduled_task_id unsigned big integer Foreign key fk_scheduled_task_id to monitored_scheduled_tasks.id, on delete cascade
type string starting, finished, failed, or skipped
meta json, nullable Event details; see Log Item Meta
created_at, updated_at timestamps created_at is the time of the event

The cascade means that deleting a task row (which the sync does for removed or renamed tasks) deletes its whole history. No index is created on name or on log_items.created_at; on very large tables you can add them in your own migration.

The MonitoredScheduledTask Model

Spatie\ScheduleMonitor\Models\MonitoredScheduledTask. All attributes are mass-assignable ($guarded = []). The timestamp columns are cast to datetimes and grace_time_in_minutes to an integer.

Method Description
logItems(): HasMany The task's log items, ordered newest first (id descending).
static findByName(string $name): ?self The row with this name, or null.
static findForTask(Event $event): ?self The row for a scheduler event, using the same name resolution as the event listeners. null for unnamed tasks.
static findForCronCheck(CronCheck $cronCheck): ?self The row matching an Oh Dear cron check by name (used by the sync).
markAsStarting(ScheduledTaskStarting $event) Records a starting log item (and starting ping, if enabled).
markAsFinished(ScheduledTaskFinished $event) Records a finished item, or a failed one for a non-zero exit code; pings Oh Dear.
markAsFailed($event) Records a failed item from a ScheduledTaskFailed or ScheduledTaskFinished event; pings Oh Dear.
markAsSkipped(ScheduledTaskSkipped $event) Records a skipped item. No ping.
markAsRegisteredOnOhDear() Sets registered_on_oh_dear_at if it is not set yet.
pingOhDear(MonitoredScheduledTaskLogItem $logItem) Dispatches the configured ping job when the task has a ping_url and the item type is pingable.
createLogItem(string $type) Creates a log item of the given type.

The mark* methods are called by the package's event listeners; you normally only use the finders and logItems().

The MonitoredScheduledTaskLogItem Model

Spatie\ScheduleMonitor\Models\MonitoredScheduledTaskLogItem. meta is cast to an array.

Member Description
TYPE_STARTING, TYPE_FINISHED, TYPE_FAILED, TYPE_SKIPPED The type constants (starting, finished, failed, skipped).
monitoredScheduledTask(): BelongsTo The task this item belongs to.
updateMeta(array $values) Replaces meta with the given array and saves.
prunable(): Builder Items with created_at older than delete_log_items_older_than_days days.

Querying the History

use Spatie\ScheduleMonitor\Models\MonitoredScheduledTask;
use Spatie\ScheduleMonitor\Models\MonitoredScheduledTaskLogItem;

// The last failure of a task, with its message or exit code.
$lastFailure = MonitoredScheduledTask::findByName('reports:send')
    ?->logItems()
    ->where('type', MonitoredScheduledTaskLogItem::TYPE_FAILED)
    ->first();

$lastFailure?->meta; // ['failure_message' => '...'] or ['exit_code' => 1, 'runtime' => ..., ...]

// All tasks that failed in the last 24 hours.
$failing = MonitoredScheduledTask::where('last_failed_at', '>=', now()->subDay())
    ->pluck('last_failed_at', 'name');

// Average runtime of the last 50 successful runs (foreground tasks only).
$average = MonitoredScheduledTask::findByName('reports:send')
    ->logItems()
    ->where('type', 'finished')
    ->limit(50)
    ->get()
    ->avg(fn ($item) => $item->meta['runtime'] ?? null);

These queries are useful for an admin dashboard or a health check endpoint. Background tasks always record a runtime of 0, so exclude them from runtime statistics.

Using Custom Models

Point the models config keys at your own classes:

// config/schedule-monitor.php
'models' => [
    'monitored_scheduled_task' => App\Models\MonitoredScheduledTask::class,
    'monitored_scheduled_log_item' => App\Models\MonitoredScheduledTaskLogItem::class,
],
namespace App\Models;

use Spatie\ScheduleMonitor\Models\MonitoredScheduledTask as BaseMonitoredScheduledTask;

class MonitoredScheduledTask extends BaseMonitoredScheduledTask
{
    protected $connection = 'monitoring';

    public function isHealthy(): bool
    {
        return is_null($this->last_failed_at)
            || $this->last_failed_at->lt($this->last_started_at ?? now()->subYears(10));
    }
}

How the package uses them:

  • At boot, the service provider binds the package model classes to your classes in the container. Everywhere the package needs a model (listeners, commands, relations), it resolves it through the container, so your class is used throughout, including the logItems() and monitoredScheduledTask() relations.
  • At boot, it also instantiates both configured classes and checks that each is an instance of the corresponding package model. If not, it throws Spatie\ScheduleMonitor\Exceptions\InvalidClassException with the message The provided class name {class} does not extend the required package class {package class}. Because this happens on every boot, a wrong class breaks every request and command, including config:clear; fix the config file directly.

Note: A few places use the package class name directly, such as the TYPE_* constants and the type hints of the OhDearPingFailed event and PingOhDearJob. Since your classes extend the package models, this works as long as you do not change those constants.

To prune with a custom log item model, pass your class to model:prune.

Pruning

// routes/console.php
use Illuminate\Support\Facades\Schedule;
use Spatie\ScheduleMonitor\Models\MonitoredScheduledTaskLogItem;

Schedule::command('model:prune', ['--model' => MonitoredScheduledTaskLogItem::class])->daily();

The log item model uses MassPrunable. Rows with a created_at at or before now() minus delete_log_items_older_than_days days are deleted in chunks, without firing model events. Task rows are never pruned.

Pruning can race with a ping job: a job for a log item that has already been pruned is discarded silently because the job sets $deleteWhenMissingModels. With the default 30-day retention this never happens in practice.

See Also