# Schedule recurring maintenance jobs

> Model planned maintenance with SchedulerEvent.rrule and exdates, let users edit one occurrence or the whole series, and store detached occurrences.

Planned preventive maintenance repeats: a boiler check every Monday, Wednesday and Friday, a daily visit to a dental practice. This recipe stores each series once with an RFC 5545 rule, lets dispatchers move a single visit or the whole series, and shows how to save the resulting data.

**Live demo: Recurring maintenance jobs** (runs on the HTML version of this page). Source of `demos/recipe-scheduler-recurring.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createScheduler, type EditScope } from '@birchui/scheduler';
import { docsTheme, field, layout, onDocsThemeChange } from './_shared';
import { WEEK_START, at, technicians, type ServiceJob, type Technician } from './_scheduler-data';

export const meta = { title: 'Recurring maintenance jobs', height: 480 };

function recurringJobs(): ServiceJob[] {
  return [
    {
      id: 'ppm-riverside',
      resourceId: 'tech-ana',
      title: 'Planned maintenance: Riverside Dental',
      customer: 'Riverside Dental',
      start: at(0, 8),
      end: at(0, 10),
      rrule: 'FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR',
    },
    {
      id: 'ppm-northside',
      resourceId: 'tech-omar',
      title: 'Boiler check: Northside School',
      customer: 'Northside School',
      start: at(0, 13),
      end: at(0, 15),
      rrule: 'FREQ=WEEKLY;BYDAY=MO,WE,FR',
      exdates: [at(2, 13)],
    },
    {
      id: 'ppm-chargers',
      resourceId: 'tech-sam',
      title: 'Charger inspection: Cedar & Stone',
      customer: 'Cedar & Stone',
      start: at(1, 9),
      end: at(1, 11),
      rrule: 'FREQ=WEEKLY;BYDAY=TU,TH',
    },
    {
      id: 'job-inverter',
      resourceId: 'tech-nora',
      title: 'Inverter swap',
      customer: 'Alpine Outfitters',
      start: at(0, 13),
      end: at(0, 17),
    },
  ];
}

const time = (d: Date) => d.toLocaleString('en-GB', { weekday: 'short', hour: '2-digit', minute: '2-digit' });

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const wholeSeries = document.createElement('input');
  wholeSeries.type = 'checkbox';
  toolbar.append(
    field('Apply to the whole series', wholeSeries),
    'Drag or resize an occurrence, or select one and press Delete.',
  );
  const end = new Date(WEEK_START);
  end.setDate(end.getDate() + 5);

  const scheduler = createScheduler<ServiceJob, Technician>(body, {
    resources: technicians,
    events: recurringJobs(),
    start: WEEK_START,
    end,
    viewPreset: 'hourAndDay',
    snap: 15,
    createOnDrag: false,
    theme: docsTheme(),
    height: '100%',
    ariaLabel: 'Recurring maintenance schedule',
  });

  const chosenScope = (): EditScope => (wholeSeries.checked ? 'all' : 'this');
  const describe = (scope: EditScope) => (scope === 'all' ? 'every occurrence' : 'this occurrence only');

  const offs = [
    scheduler.on('eventDrop', (change) => {
      if (!change.occurrence) {
        status.textContent = `${change.event.title} moved to ${time(change.start)}.`;
        return;
      }
      change.scope = chosenScope();
      status.textContent = `Moved ${describe(change.scope)} of ${change.occurrence.event.title} from ${time(change.occurrence.start)} to ${time(change.start)}.`;
    }),
    scheduler.on('eventResize', (change) => {
      if (!change.occurrence) return;
      change.scope = chosenScope();
      status.textContent = `Resized ${describe(change.scope)} of ${change.occurrence.event.title}.`;
    }),
    scheduler.on('eventRemove', (change) => {
      if (!change.occurrence) {
        status.textContent = `${change.event.title} removed.`;
        return;
      }
      change.scope = chosenScope();
      const series = scheduler.getEventById(change.occurrence.id);
      const skipped = (series?.exdates?.length ?? 0) + (change.scope === 'this' ? 1 : 0);
      status.textContent =
        change.scope === 'all'
          ? `Removed the series ${change.occurrence.event.title}.`
          : `Skipped ${time(change.occurrence.start)}. The series now has ${skipped} exception dates.`;
    }),
  ];
  status.textContent = 'Changes to recurring jobs appear here.';
  const stopTheme = onDocsThemeChange((theme) => scheduler.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    scheduler.destroy();
  };
}
```

## Steps

1. Give the master event an `rrule`, and optionally `exdates` for visits that are skipped.
2. In `eventDrop`, `eventResize` and `eventRemove`, check for `occurrence` and set `scope` to `'this'` or `'all'`.
3. Persist the masters and any detached occurrences, matched by `recurringEventId` and `recurrenceId`.

## Define a series

```ts title="maintenance-plan.ts"
import type { SchedulerEvent } from '@birchui/scheduler';

interface MaintenanceJob extends SchedulerEvent {
  site: string;
  contractRef: string;
}

export const maintenanceJobs: MaintenanceJob[] = [
  {
    id: 'ppm-northside',
    resourceId: 'tech-omar',
    title: 'Boiler check',
    site: 'Northside School',
    contractRef: 'PPM-2026-118',
    start: '2026-12-07T13:00',
    end: '2026-12-07T15:00',
    rrule: 'FREQ=WEEKLY;BYDAY=MO,WE,FR;UNTIL=20270331T150000',
    exdates: ['2026-12-23T13:00', '2026-12-25T13:00'],
  },
  {
    id: 'ppm-riverside',
    resourceId: 'tech-ana',
    title: 'Daily plant room check',
    site: 'Riverside Dental',
    contractRef: 'PPM-2026-131',
    start: '2026-12-07T08:00',
    end: '2026-12-07T08:45',
    rrule: 'FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR',
  },
];
```

`start` and `end` describe the first visit; the rule repeats it. The rules are read by the same engine as `@birchui/calendar`, so `FREQ`, `INTERVAL`, `COUNT`, `UNTIL`, `BYDAY` (including `1MO` and `-1FR`), `BYMONTHDAY`, `BYMONTH` and `BYSETPOS` all work. Occurrences are generated only for the visible range.

Each occurrence is shown as an event with the id `'<series id>@<recurrence id>'`, such as `'ppm-northside@2026-12-09T13:00:00'`, and carries `recurringEventId` (the series id) and `recurrenceId` (its original start). `getEvents()` returns the series once; `getEventById` and `getEventsInRange` also find occurrences.

## Ask for the scope

When a user drags, resizes or deletes an occurrence, the event payload has an `occurrence` and `scope: 'this'`. The change is applied after your listener returns, with whatever `scope` the payload has then:

```ts title="recurring-edits.ts"
import type { EditScope } from '@birchui/scheduler';

const wholeSeries = document.querySelector<HTMLInputElement>('#apply-to-series')!;
const chosenScope = (): EditScope => (wholeSeries.checked ? 'all' : 'this');

scheduler.on('eventDrop', (change) => {
  if (change.occurrence) change.scope = chosenScope();
});

scheduler.on('eventResize', (change) => {
  if (change.occurrence) change.scope = chosenScope();
});

scheduler.on('eventRemove', (change) => {
  if (!change.occurrence) return;
  change.scope = window.confirm(`Cancel every visit of ${change.occurrence.event.title}?`) ? 'all' : 'this';
});
```

| Scope | Move or resize | Remove |
| --- | --- | --- |
| `'this'` | Adds the occurrence's `recurrenceId` to the series' `exdates` and adds a detached event for the moved visit. | Adds the occurrence to `exdates`. |
| `'all'` | Shifts the whole series by the same amount. Moving to another weekday shifts `BYDAY` and the existing `exdates` with it. | Removes the series. |

The `occurrence` object describes the visit that was touched:

**`SchedulerOccurrence`** (interface from `@birchui/scheduler`, full reference: https://docs.birchui.com/api/scheduler.md)

```ts
interface SchedulerOccurrence<TEvent extends SchedulerEvent = SchedulerEvent>
```

| Property | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `occurrenceId` | `string` |  |
| `recurrenceId` | `string` |  |
| `start` | `Date` |  |
| `end` | `Date` |  |
| `event` | `TEvent` |  |

`occurrence.event` is the master; `occurrence.start` and `occurrence.end` are the visit's times before the change.

## The detached occurrence

With scope `'this'`, the moved visit becomes its own event: a copy of the master without `rrule` and `exdates`, with the occurrence id, `recurringEventId` and `recurrenceId`:

```json
{
  "id": "ppm-northside@2026-12-09T13:00:00",
  "resourceId": "tech-omar",
  "title": "Boiler check",
  "site": "Northside School",
  "contractRef": "PPM-2026-118",
  "start": "2026-12-09T15:30:00.000Z",
  "end": "2026-12-09T17:30:00.000Z",
  "recurringEventId": "ppm-northside",
  "recurrenceId": "2026-12-09T13:00:00"
}
```

Store detached events next to their master. When you load the schedule again, pass both: the master's `exdates` hide the original visit and the detached event shows the moved one.

## Save the result

The payloads of `eventDrop` and friends fire **before** the change is applied, so they cannot tell you the final master. Persist from `historyChange` instead, which reports every event that changed, including both halves of a detached edit:

```ts title="persist-recurring.ts"
scheduler.on('historyChange', ({ action, changes }) => {
  if (action === 'clear') return;
  for (const { id, after } of changes) {
    if (after) void api.put(`/api/maintenance-jobs/${encodeURIComponent(id)}`, after);
    else void api.delete(`/api/maintenance-jobs/${encodeURIComponent(id)}`);
  }
});
```

A `'this'` move produces two changes: the master with a new `exdates` entry, and the new detached event. See [Save scheduler changes to a server](https://docs.birchui.com/recipes/scheduler-save-to-server.md) for batching and error handling.

## Edit from code

`updateEvent(occurrenceId, patch)` and `removeEvent(occurrenceId)` edit a single occurrence the same way scope `'this'` does. To change the series, update the master by its own id:

```ts
scheduler.updateEvent('ppm-northside@2026-12-16T13:00:00', { resourceId: 'tech-li' });
scheduler.removeEvent('ppm-riverside@2026-12-24T08:00:00');
scheduler.updateEvent('ppm-riverside', { rrule: 'FREQ=WEEKLY;BYDAY=MO,WE,FR' });
```

## Pitfalls

- **Set `scope` synchronously.** The scheduler reads it as soon as your listener returns. For an asynchronous dialog, leave scope at `'this'`; if the user then picks the whole series, call `undo()` to revert the single-visit edit and change the master with `updateEvent`.
- **`historyChange` needs history.** It does not fire when `undoRedo` is `false`.
- **Invalid rules.** An `rrule` that cannot be parsed shows the event once, with a console warning. Unsupported rule parts are ignored with a warning.
- **Wall-clock time.** Occurrences keep their wall-clock time in the scheduler's `timeZone` across daylight saving changes.

## Related

- [Recurrence in the Event Calendar](https://docs.birchui.com/calendar/recurrence.md#editing-occurrences), which follows the same rules.
- [iCalendar feeds](https://docs.birchui.com/recipes/calendar-ical-feed.md), which read and write the same detached-occurrence shape.
- [Undo and redo in the scheduler](https://docs.birchui.com/recipes/scheduler-undo-redo.md).
