6. Clean up every hour

Scheduled jobs: work that runs on the clock, not on a call.

2 MIN READView Markdown ↗

The chat keeps a week of history. Older messages, and their photos, should go away without anyone calling anything. That is a job.

The backend#

Add every to the import, and register the job below routes:

TypeScript
import { ApiError, caller, event, every, files, online, type Routes } from 'arkapi/server'
TypeScript
every('1h', function cleanup() {
  const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
  const old = db.query<{ photo: string }, [number]>('select photo from messages where at < ? and photo is not null').all(weekAgo)
  db.run('delete from messages where at < ?', [weekAgo])
  old.forEach((row) => files.remove(row.photo))
})
  • every takes milliseconds or '30s', '5m', '1h'. For a time of day, daily('03:00', fn) runs once a day, in UTC.
  • Runs line up with the clock: an hourly job runs at the start of each hour, not an hour after the last deploy.
  • Each run writes job cleanup ok 3ms, or its error, to the logs, and refreshes live queries, so open screens drop the old messages right away.
  • A run is skipped while the previous one is still going, and only the active version runs jobs, so a deploy never runs one twice.
  • A job has no calling device: caller() does not work inside it.

This is the whole backend. Everything from here is about shipping it.

Next: ship it.

Tab to navigate results · Enter to open · Esc to close