Background jobs
Report each cron tick, queue message, or background task as a Job Run with its own trace. Complete the Node.js quickstart before running these examples.
Monitor a job
Wrap one execution of a job, such as a cron tick, a queue message, or one loop iteration, with withJobMonitor. Each execution is reported as a Job Run with its own trace, even when the job is triggered from inside a web request. Database queries and outgoing calls made inside the job belong to that run.
Pass the job's name and the function to run. This example uses node-cron:
import { withJobMonitor } from "@vigilon/node";
import cron from "node-cron";
cron.schedule("0 3 * * *", () =>
withJobMonitor({ name: "sync-users", schedule: "0 3 * * *" }, async () => {
await syncUsers();
}),
);
The same wrapper works for queue processors and plain intervals:
import { withJobMonitor } from "@vigilon/node";
import { Worker } from "bullmq";
// BullMQ: wrap the processor callback
new Worker("emails", (bullJob) =>
withJobMonitor({ name: "send-email" }, () => sendEmail(bullJob.data)),
);
// Plain interval
setInterval(
() => withJobMonitor({ name: "refresh-cache" }, () => refreshCache()),
60_000,
);
Name and schedule
name is required and should stay the same across runs. Use sync-users, not a different name such as sync-user-42 for every item. A new name creates a new job in Vigilon, so per-item names never build up a history of runs.
schedule is an optional cron expression used for last-run and stale-job detection. It describes when your scheduler is expected to run the job; it does not schedule or execute anything. Keep using your cron service, queue, or task scheduler.
Return values and errors
Sync and async functions both work. The return value, or promise, passes through unchanged. Errors that leave the job are recorded on the run and thrown again, so your retry logic still works. If you catch an error inside the job, call recordException(error) yourself.
Vigilon has to be running before a job executes. With the --import flag from the quickstart, it always is. A job that runs before startup still does its work, but Vigilon does not receive a Job Run for it.
Scripts that exit
Vigilon sends data in small batches in the background. A script that finishes right after its job, such as a one-off task or a scheduled container, can exit before the last batch is sent. Await shutdown() before the process exits:
import { shutdown, withJobMonitor } from "@vigilon/node";
try {
await withJobMonitor({ name: "sync-users", schedule: "0 3 * * *" }, () =>
syncUsers(),
);
} finally {
await shutdown();
}
shutdown() never throws, so a problem sending data cannot crash your script or hide the result of the job. Call it once, when all the work is done, and await it before calling process.exit(). Long-running servers do not need it, and AWS Lambda is handled automatically.