Scheduled jobs

Work that runs every hour or every night.

2 MIN READView Markdown ↗

Register jobs at the top level of an api file:

TypeScript
import { every, daily } from 'arkapi/server'

every('1h', function cleanupHistory() {
  db.run('delete from messages where at < ?', [Date.now() - 7 * 86400000])
})

daily('02:30', async function nightlyDigest() {
  await fetch(process.env.DIGEST_URL!, { method: 'POST' })
})

every takes milliseconds or '30s', '5m', '1h'. daily takes HH:MM in UTC.

  • A run is skipped while the previous one is still running.
  • Each run writes job cleanupHistory ok 12ms, or its error, to the logs, then refreshes live data.
  • Only the active version runs jobs, so a deploy never runs a job twice.
  • Jobs have no calling device; caller() does not work inside them.
  • Runs missed while the app was down are not repeated.

Testing a job#

Put the logic in a plain module outside the *.api.ts files, with an explicit time, and call it from a Bun test. Exporting it from an api file would make it an endpoint.

TypeScript
// retention.ts
import { Database } from 'bun:sqlite'

export function cleanupBefore(db: Database, cutoff: number): number {
  return db.run('DELETE FROM photos WHERE created_at < ?', [cutoff]).changes
}
TypeScript
// photos.api.ts
import { Database } from 'bun:sqlite'
import { daily } from 'arkapi/server'
import { cleanupBefore } from './retention'

const db = new Database('app.db')
daily('02:30', function cleanup() { cleanupBefore(db, Date.now() - 30 * 86400000) })
TypeScript
// retention.test.ts: run with `bun test`
import { expect, test } from 'bun:test'
import { Database } from 'bun:sqlite'
import { cleanupBefore } from './retention'

test('removes photos older than the cutoff', () => {
  const db = new Database(':memory:')
  db.run('CREATE TABLE photos (id INTEGER PRIMARY KEY, created_at INTEGER)')
  db.run('INSERT INTO photos (created_at) VALUES (100), (300)')
  expect(cleanupBefore(db, 200)).toBe(1)
})
Tab to navigate results · Enter to open · Esc to close