---
title: "6. Clean up every hour"
description: "Scheduled jobs: work that runs on the clock, not on a call."
url: "https://arkapi.emincanozcan.com/docs/tutorial-cleanup"
---

# 6. Clean up every hour

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

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`:

```ts
import { ApiError, caller, event, every, files, online, type Routes } from 'arkapi/server'
```

```ts
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](/docs/tutorial-ship.md).
