Jobs
Jobs are documents in <AUTH_PREFIX>jobs (mc_jobs), managed with /system/jobs (useMongocampApiJobs()). Each job names a handler by its className and runs on a cron schedule.
{
"name": "NightlyReport",
"group": "Reports",
"className": "my.app.ReportJob",
"description": "Sends the report",
"cronExpression": "0 0 2 * * *",
"priority": 1
}Cron expressions
The syntax is that of croner, with an optional seconds field:
| Expression | Meaning |
|---|---|
*/5 * * * * * | every 5 seconds |
0 */5 * * * * | every 5 minutes |
0 0 2 * * * | daily at 02:00 |
@daily, @hourly | shortcuts |
0 0 12 * * 5L | 12:00 on the last Friday of the month |
An invalid expression answers 400. A stored job whose expression croner does not accept is listed as not scheduled, with the reason. Fix it with PATCH /system/jobs/{group}/{name}.
Handlers
A handler is a function that receives the run:
import type { JobHandler } from '@sfxcode/mongocamp-server-core'
const report: JobHandler = async ({ config, startedAt, manual }) => {
await sendReport(startedAt)
}
await createMongocampServer({
jobs: {
handlers: { 'my.app.ReportJob': report },
enabled: true, // false: do not run jobs on their schedule in this instance
},
})GET /system/jobs/classes lists the registered handler names. A job whose class has no handler cannot be added (404, code 4042). POST /system/jobs/{group}/{name} runs a job immediately (manual: true). Every run publishes job:executed.
The server registers one job itself: CleanUpTokenJob (class dev.mongocamp.server.jobs.CleanUpTokenJob, every five minutes) removes expired tokens.
Handlers in a Nuxt app
The embedded server is created by the module, so register handlers in a Nitro plugin on mongocamp:ready:
// server/plugins/jobs.ts
import { definePlugin } from 'nitro'
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook('mongocamp:ready', (server) => {
server.registerJobHandler('my.app.ReportJob', async ({ startedAt }) => {
await sendReport(startedAt)
})
})
})A listener of mongocamp:ready that is registered after the server is ready — a plugin that runs after another plugin already awaited useMongocampCore() — is called at once with the server (since 3.1.0; in 3.0.0 it was never called, and its queue handlers never ran).
Registering a handler schedules the stored jobs of that class right away, and adds it to GET /system/jobs/classes. registerJobHandler returns a function that removes the handler and stops those jobs again. It works the same on a server you host yourself.
Several instances
Every instance with an active scheduler runs the jobs; there is no lock between instances. Switch the scheduler off in all but one instance, or write handlers that can run concurrently:
| Host | Switch |
|---|---|
| Standalone server | JOBS_ENABLED=false |
| Nuxt module | server.jobs: false, or JOBS_ENABLED=false |
| Own host | jobs: { enabled: false }, or JOBS_ENABLED=false |
An instance with the scheduler off still lists the jobs and runs them by request (POST /system/jobs/{group}/{name}). JOBS_ENABLED is not stored in the database, because a stored value would switch off every instance.
Job queue (3.0)
Cron jobs run on a schedule; the queue runs one-off jobs — send a mail, render a report, call a webhook — once, with retries, on whichever instance is free.
// server/plugins/queue.ts: the handlers (a Nuxt app; standalone: server.queue.handle(...) after createMongocampServer)
import { definePlugin } from 'nitro'
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook('mongocamp:ready', (server) => {
server.queue.handle<{ to: string }>('sendWelcome', async ({ payload, attempt }) => {
await mailer.send({ to: payload.to, subject: 'Welcome' }) // a throw is a failed attempt
})
})
})
// anywhere in server code
const core = await useMongocampCore()
await core.enqueue('sendWelcome', { to: 'ada@example.org' }, { delay: '5m', retries: 5, key: 'welcome:ada' })Option of enqueue | |
|---|---|
delay / runAt | wait before the first run (milliseconds or a duration like 5m) / a time |
retries | runs after a failure, default 3 (so 4 attempts) |
backoff | { type: 'exponential' | 'fixed', delayMs }, default exponential from 1 s (1 s, 2 s, 4 s, …, at most an hour) |
key | dedupe: while a job with the key is pending or running, enqueue answers that job |
- The jobs are documents of
mc_queue. A worker claims a job atomically with a lease (QUEUE_LEASE, default 60 s) that it renews while the handler runs; a job runs once even with several instances. A job whose instance crashed is claimed again when its lease ran out. - After the last attempt a job stays
failed(dead letter, eventqueue:failed) until an administrator retries it (POST /system/queue/{id}/retry) or deletes it (DELETE /system/queue/{id}; a running job answers409, code4094, since 3.1.0);GET /system/queue?state=failedlists them. Done jobs are removed afterQUEUE_KEEP_DONE(7 days). - An instance works on the queue only when it has handlers and
QUEUE_WORKERis on (default);QUEUE_CONCURRENCY(default 1) jobs at once, polled everyQUEUE_POLL_INTERVAL(1 s; a job enqueued on the instance starts at once). - The DevTools tab Queue shows the counts per state, the failed and the latest jobs.
Auth mails through the queue
The mails of the auth flows are an event; putting them on the queue retries a mail server that is down:
nitroApp.hooks.hook('mongocamp:ready', (server) => {
server.queue.handle<AuthMail>('authMail', ({ payload }) => mailer.send({ to: payload.to, subject: payload.kind, text: payload.url }))
})
nitroApp.hooks.hook('mongocamp:auth:mail', async (mail) => {
const core = await useMongocampCore()
await core.enqueue('authMail', mail, { retries: 5 })
})