{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreihosddy6dpwie75z2qtarm26t2gwg7axdln3qilwi4oz5kiu2ra5y",
"uri": "at://did:plc:25rdn5elo5izoxrmtis34zuk/app.bsky.feed.post/3mpvd3jyc5c72"
},
"coverImage": {
"$type": "blob",
"ref": {
"$link": "bafkreiej7fjkivvohrumjxbh7p6ucvp7qzf3zxxwlgvw47af7d7gadtdm4"
},
"mimeType": "image/webp",
"size": 20600
},
"path": "/zsevic/cron-jobs-and-schedulers-with-bullmq-405a",
"publishedAt": "2026-07-05T09:35:36.000Z",
"site": "https://dev.to",
"tags": [
"node",
"bullmq",
"redis",
"cron",
"Postgres and Redis containers with Docker Compose",
"Book a consultation",
"@nestjs",
"@Processor",
"@Module",
"@Injectable",
"@InjectQueue",
"@Cron"
],
"textContent": "In-process cron (`node-cron`, `@nestjs/schedule`, OS crontab) runs inside one Node process. That is fine for a single instance, but it does not survive restarts gracefully, deduplicate across replicas, or share infrastructure with your other background jobs.\n\nBullMQ stores queues and schedulers in **Redis**. **Job Schedulers** (BullMQ 5.16+) are the recommended way to enqueue recurring work on a cron pattern or fixed interval. The same workers that process one-off jobs also process scheduled ones, with retries, backoff, and concurrency you already get from BullMQ.\n\nThis post covers Job Schedulers in plain Node.js, operations and pitfalls, a NestJS setup with `@nestjs/bullmq`, and a runnable demo with a fast cron heartbeat and a daily cleanup cron.\n\n### Prerequisites\n\n * Node.js version 26\n * Redis at `redis://localhost:6379` (included in the demo `docker-compose.yml`, or use Postgres and Redis containers with Docker Compose)\n * `npm i bullmq`\n\n\n\nFor the NestJS section: `npm i @nestjs/bullmq bullmq`\n\nBullMQ 2.0+ does **not** require a separate `QueueScheduler` instance. Use the **Job Scheduler** API (`upsertJobScheduler`), not the deprecated `repeat` option on `queue.add()`.\n\n### Mental model\n\nPiece | Role\n---|---\n**Queue** | Holds jobs waiting to run\n**Worker** | Executes jobs\n**Job Scheduler** | Factory that enqueues jobs on a schedule\n**Scheduled job** | A job instance produced by a scheduler\n\nA scheduler id is stable across deploys. Calling `upsertJobScheduler` with the same id updates the schedule in place instead of creating duplicates.\n\n### Queue and worker\n\nShare one Redis connection config between the queue and the worker:\n\n\n\n import { Queue, Worker } from 'bullmq';\n\n const connection = { host: 'localhost', port: 6379 };\n\n const queue = new Queue('reports', { connection });\n\n const worker = new Worker(\n 'reports',\n async (job) => {\n console.log(`[${job.name}]`, new Date().toISOString(), job.data);\n },\n { connection },\n );\n\n worker.on('failed', (job, error) => {\n console.error(job?.name, error.message);\n });\n\n\nStart the worker before or shortly after registering schedulers. If no worker is running, jobs accumulate in Redis until one picks them up.\n\n### Cron schedulers\n\nBullMQ uses a **6-field** cron expression (optional seconds). A fast pattern for demos and heartbeats:\n\n\n\n await queue.upsertJobScheduler(\n 'report-heartbeat',\n { pattern: '*/10 * * * * *' },\n {\n name: 'heartbeat',\n data: { source: 'scheduler' },\n opts: {\n attempts: 3,\n backoff: { type: 'exponential', delay: 1000 },\n removeOnComplete: 50,\n },\n },\n );\n\n\nDaily cleanup at 03:15 in a specific timezone:\n\n\n\n await queue.upsertJobScheduler(\n 'daily-cleanup',\n { pattern: '0 15 3 * * *', tz: 'Europe/Berlin' },\n {\n name: 'cleanup',\n data: { scope: 'stale-sessions' },\n opts: { attempts: 3 },\n },\n );\n\n\nSet `tz` when the job must fire at a local wall-clock time. For millisecond intervals instead of cron, use `every` (mutually exclusive with `pattern`).\n\nOther useful repeat options:\n\nOption | Purpose\n---|---\n`limit` | Maximum number of iterations\n`immediately` | Run once now, then follow the schedule\n`startDate` / `endDate` | Bound the scheduler to a time window\n\n### Register schedulers on startup\n\nKeep scheduler registration in a dedicated bootstrap script or `onModuleInit` hook so deploys upsert the same ids:\n\n\n\n // scheduler.js\n import { Queue } from 'bullmq';\n\n const connection = { host: 'localhost', port: 6379 };\n const queue = new Queue('reports', { connection });\n\n await queue.upsertJobScheduler(\n 'report-heartbeat',\n { pattern: '*/10 * * * * *' },\n { name: 'heartbeat', data: { source: 'scheduler' } },\n );\n\n await queue.upsertJobScheduler(\n 'daily-cleanup',\n { pattern: '0 15 3 * * *', tz: 'Europe/Berlin' },\n { name: 'cleanup', data: { scope: 'stale-sessions' } },\n );\n\n const schedulers = await queue.getJobSchedulers();\n console.log(\n 'Active schedulers:',\n schedulers.map((item) => ({ key: item.key, pattern: item.pattern })),\n );\n\n await queue.close();\n\n\nTo remove a scheduler:\n\n\n\n await queue.removeJobScheduler('daily-cleanup');\n\n\nShut down cleanly on `SIGINT` / `SIGTERM`: `await worker.close()` and `await queue.close()`.\n\n### NestJS with `@nestjs/bullmq`\n\nNestJS wraps BullMQ queues and workers as providers. Register Redis once, register the queue, inject it into a service that upserts schedulers on startup, and process jobs in a `@Processor` class.\n\n\n\n // app.module.ts\n import { Module } from '@nestjs/common';\n import { BullModule } from '@nestjs/bullmq';\n import { ReportsProcessor } from './reports.processor';\n import { ReportsSchedulerService } from './reports-scheduler.service';\n\n @Module({\n imports: [\n BullModule.forRoot({\n connection: { host: 'localhost', port: 6379 },\n }),\n BullModule.registerQueue({ name: 'reports' }),\n ],\n providers: [ReportsProcessor, ReportsSchedulerService],\n })\n export class AppModule {}\n\n\n\n // reports-scheduler.service.ts\n import { Injectable, OnModuleInit } from '@nestjs/common';\n import { InjectQueue } from '@nestjs/bullmq';\n import { Queue } from 'bullmq';\n\n @Injectable()\n export class ReportsSchedulerService implements OnModuleInit {\n constructor(@InjectQueue('reports') private readonly reportsQueue: Queue) {}\n\n async onModuleInit() {\n await this.reportsQueue.upsertJobScheduler(\n 'report-heartbeat',\n { pattern: '*/10 * * * * *' },\n { name: 'heartbeat', data: { source: 'nestjs' } },\n );\n\n await this.reportsQueue.upsertJobScheduler(\n 'daily-cleanup',\n { pattern: '0 15 3 * * *', tz: 'Europe/Berlin' },\n { name: 'cleanup', data: { scope: 'stale-sessions' } },\n );\n }\n }\n\n\n\n // reports.processor.ts\n import { Processor, WorkerHost } from '@nestjs/bullmq';\n import { Job } from 'bullmq';\n\n @Processor('reports')\n export class ReportsProcessor extends WorkerHost {\n async process(job: Job): Promise<void> {\n console.log(`[${job.name}]`, new Date().toISOString(), job.data);\n }\n }\n\n\n`ReportsSchedulerService` runs when the Nest app boots, so schedulers are upserted on every deploy. `ReportsProcessor` is the worker; Nest registers it automatically unless you set `manualRegistration` on `BullModule.forRoot`.\n\n`@nestjs/schedule` (`@Cron()`) is still a good fit for trivial timers inside one instance. Prefer BullMQ schedulers when you already use Redis queues, run multiple replicas, or need the same retry and observability model as the rest of your background jobs.\n\n### Pitfalls\n\n * **Worker must be running** - schedulers enqueue jobs; something must consume them.\n * **Busy queues slip** - BullMQ creates the next scheduled job when the previous one **starts** processing. Under load, ticks can be less frequent than `every` or the cron interval suggests.\n * **`pattern` vs `every`** - mutually exclusive; pick one per scheduler.\n * **Timezone** - omit `tz` and cron runs in the server default zone; set it explicitly for \"9 AM local\" jobs.\n * **Legacy`repeat` on `add()`** - deprecated from BullMQ 5.16; use `upsertJobScheduler` for new code.\n\n\n\n### When to use what\n\nApproach | Good for\n---|---\n`@nestjs/schedule` / `node-cron` | Single instance, simple in-process timers\n**BullMQ Job Schedulers** | Multi-instance apps, shared Redis, retries with async jobs\nExternal cron + HTTP | Fire-and-forget HTTP triggers without queue semantics\n\n### Need help with your project?\n\nGet personalized advice on your architecture, code, or career in a 45-minute 1-on-1 consultation.\n\n→ Book a consultation",
"title": "Cron jobs and schedulers with BullMQ"
}