Usage | laravel-schedule-monitor-rust | Spatie       

 SPATIE  

laravel-schedule-monitor-rust
=============================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-schedule-monitor-rust](https://spatie.be/docs/laravel-schedule-monitor-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-schedule-monitor-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/usage)
- [ Monitoring and Oh Dear ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/monitoring)
- [ Testing ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/changelog)
- [ Customization ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/customization)
- [ Registering application commands ](https://spatie.be/docs/laravel-schedule-monitor-rust/v1/scheduled-commands)

 Usage
=====

###  On this page 

1. [ Table names ](#content-table-names)
2. [ Native registration ](#content-native-registration)
3. [ Timezones ](#content-timezones)

1. Define the monitor once.
2. Apply each definition to its native task with `register`, which sets the name and schedule.
3. Add arguments, locks and completion hooks through the native task API.

This example runs a harmless callback through the real scheduler and checks the persisted history:

```
use laravel::{Application, config::Env};
use laravel::config::database::ConnectionConfig;
use laravel::testing::MakesConsoleRequests;
use spatie_schedule_monitor::{MonitoredTask, ScheduleMonitor};

let cleanup = MonitoredTask::new("cleanup", "0 2 * * 1")?
    .timezone("Europe/Brussels")?
    .grace_minutes(45);
let monitor = ScheduleMonitor::new([cleanup.clone()])?
    .table_names("rust_scheduled_tasks", "rust_scheduled_task_logs")?;
let builder = Application::configure()
    .replace_env(Env::default())
    .with_config(|config, _| {
        let mut connection = ConnectionConfig::new("sqlite::memory:");
        connection.max_connections = 1;
        config.database.default = "monitor".into();
        config.database.add_connection("monitor", connection);
    })
    .with_schedule(move |schedule, _| {
        cleanup.register(schedule.call(|| async {}))
            .without_overlapping();
    });
let app = monitor.clone().install(builder).create();
app.travel_to("2026-11-30T01:00:00Z".parse::<laravel::time::Timestamp>()?);

app.scope(async || monitor.migrate().await).await?;
app.command("schedule-monitor:sync").await.assert_successful();
app.command("schedule:run").await.assert_successful();

app.scope(async || {
    let logs = monitor.logs("cleanup").await?;
    assert_eq!(logs[0].kind, "starting");
    assert_eq!(logs[1].kind, "finished");
    assert_eq!(logs[1].exit_code, Some(0));
    Ok::<_, laravel::Error>(())
}).await?;
```

- Select your application's normal database connection in production. This example uses in-memory SQLite.
- Call `monitor.migrate()` from a migration, not on every web request. It creates missing tables and adds nullable package columns to an existing monitor schema.
- Migration checks both tables before changing either. It rejects missing base columns without converting or dropping another application's tables.

Table names
-----------------------------------------------------------------------------------------

- Defaults are `monitored_scheduled_tasks` and `monitored_scheduled_task_log_items`.
- Select unused names with `.table_names(tasks, logs)?` before cloning or installing. Use the same configuration in migrations, commands and workers.
- Names must be distinct ignoring case, use ASCII letters, digits or underscores, start with a letter or underscore, and contain at most 46 bytes. The limit leaves room for native index-name suffixes.
- Qualified database/schema names are not accepted. The package uses the application's default connection.
- Migration, sync, listeners, reads, pruning and the outbox all use these names. Changing names does not move existing data.
- A custom `MonitorStore` owns its own model/table mapping. See [customization](customization).

Native registration
-----------------------------------------------------------------------------------------------------------------

- Fully configure a `MonitoredTask`, clone it into the monitor, then use its infallible `register(task)` inside `with_schedule`. Keep cloned definitions identical.
- Use `monitor.register(name, task)?` when a fallible name lookup is useful. Both methods share the same registration code.
- Use `schedule.command("command:name --option")` for commands. The monitor observes exit codes, exceptions and hook failures until the command exits.
- Queued native jobs report dispatch success, not worker completion. Commands can run alongside other tasks without being detached.
- Install once, using a unique name per schedule. Definitions alone do not schedule work. The framework cannot enumerate tasks publicly, so sync cannot detect unattached definitions; they eventually become late.
- `monitor.definitions()` includes every local definition. `monitor.cron_checks()` contains only remote-enabled tasks and must not be used to register local schedules.
- Output storage is opt-in. Set `.store_output(true)` on the definition and `.send_output_to(path)` on its native command or process. The monitor reads the file after success or failure.
- Callbacks and queued jobs have no process output file. Append-mode files include earlier output, and capture is not size-limited. Do not store sensitive or unbounded output.
- Cron expressions have minute resolution and use union semantics when both day fields are restricted. Do not override the name or expression after registration or add sub-minute repeats. Events expose expression drift but not repeat metadata or explicit-name identity.

Timezones
-----------------------------------------------------------------------------------

- UTC is the default. `.timezone("Europe/Brussels")?` selects Brussels wall time. Unavailable IANA names return `RegistrationError::UnsupportedTimezone`.
- Persisted events and deadlines use UTC epoch milliseconds. Grace uses elapsed minutes, not wall-clock arithmetic.
- For non-UTC schedules, `register` adds a native every-minute carrier and `when` predicate. The predicate and deadlines use the same zoned cron. Native hooks and locks remain intact.
- Carrier minutes outside the local cron create no logs, pings or expected completions. `schedule:list` shows the carrier; `monitor.tasks()` and `cron_checks()` show the local expression and timezone.
- Register tasks once, even when not due at startup. Do not condition registration on the current time or add an hourly gate.
- Register before custom predicates. Native time windows use UTC; apply them deliberately to local schedules.
- The gate reads the application clock during predicate evaluation. Slow predicates or a preceding long `blocking()` task can delay evaluation past a local minute. The framework does not expose its invocation-minute snapshot to predicates; a missed occurrence still becomes late.
- Forward clock changes skip nonexistent local minutes. Backward changes run repeated minutes twice. Brussels daily `02:30` has no occurrence on March 29, 2026, and two on October 25 at `00:30Z` and `01:30Z`.
- Success at the first repeated minute leaves the second expected. Overlap locks can skip the second if the first is still running, but skips do not count as success.
- Daily midnight schedules have 23 or 25 elapsed hours between occurrences across Brussels DST changes. A missed deadline stays attached to its original instant, even after later periods pass.
- Keep timezone databases current on scheduler and monitoring hosts.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
