DEV Community

Arpit Savaj
Arpit Savaj

Posted on

⏰ Cron Jobs in NestJS Using @nestjs/schedule

Image description

Ever wished your app could do things automatically — like publish a blog post at a specific time, send reminders every Monday, or clear cache every night?

That’s where cron jobs shine. If you're using NestJS, the @nestjs/schedule package makes it super simple to schedule tasks in your backend.

In this post, I’ll walk you through how to use static, dynamic, and timezone-aware cron jobs in NestJS — explained with fun real-life examples you’ll never forget!😄

What is a Cron Job?

A cron job is just a scheduled task that your server runs automatically — based on time or intervals.

Think of it like telling your app:

"Wake me up at 6:00 AM every day!"or"Publish this blog post tomorrow at 9:00 AM."

We’ll look at 3 useful types:

  • Static cron jobs – fixed schedule, defined in code
  • Dynamic cron jobs – scheduled at runtime
  • Timezone-aware cron jobs – respect user’s time zone

Let’s dive into them one-by-one. 👇

Install the Scheduler Package

Before using any cron jobs in NestJS, install the official scheduler package:

npm install --save @nestjs/schedule 
Enter fullscreen mode Exit fullscreen mode

And don’t forget to register the ScheduleModule in your root module:

import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { TaskService } from './task.service';

@Module({
    imports: [ScheduleModule.forRoot()],
    providers: [TaskService],
})
export class AppModule { } 
Enter fullscreen mode Exit fullscreen mode

Now you’re ready to schedule tasks like a pro! 🚀

1. Static Cron Jobs – “Like setting a daily alarm for gym”

Real-life example:

You wake up at 6:00 AM every single day to go to the gym. It’s a daily routine.

This is exactly like a static cron job — hardcoded and consistent.

import { Cron } from '@nestjs/schedule';
import { Injectable } from '@nestjs/common';

@Injectable()
export class TaskService {
    @Cron('0 6 * * *', { timeZone: 'Asia/Kolkata', })
    handleGymAlarm() {
        console.log('⏰ Time to hit the gym at 6:00 AM IST!');
    }
} 
Enter fullscreen mode Exit fullscreen mode

0 6 * * * = every day at 6:00 AM.

Refer to crontab.guru to test and understand Cron syntax.

2. Dynamic Cron Jobs – “Like setting an alarm for a special day”

Real-life example:

You’ve got a trip tomorrow, so you set a one-time alarm at 4:30 AM — just for tomorrow.

Or…

You schedule a blog post to go live tomorrow at 9:00 AM.

That’s a dynamic cron job — created at runtime, based on user input or events.

import { Injectable } from "@nestjs/common";
import { SchedulerRegistry } from "@nestjs/schedule";
import * as schedule from "node-schedule";
@Injectable()
export class TaskService {
  constructor(private schedulerRegistry: SchedulerRegistry) {}
  scheduleOneTimeAlarm(postId: string, date: Date) {
    const job = schedule.scheduleJob(date, () => {
      console.log(`Blog post ${postId} published at ${date}`);
    });
    this.schedulerRegistry.addCronJob(postId, job);
    console.log(`Job '${postId}' scheduled at ${date}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

You can now dynamically schedule blog posts, reminders, or any task based on runtime logic!

How to Cancel a Scheduled Post

Sometimes you may want to cancel a job after it's created — e.g., the user cancels a blog post.

cancelScheduledJob(name: string) {
    const job = this.schedulerRegistry.getCronJob(name);
    if (job) {
        job.stop();
        this.schedulerRegistry.deleteCronJob(name);
        console.log(`Job '${name}' stopped and removed.`);
    }
    else { console.log(`Job '${name}' not found.`); }
} 
Enter fullscreen mode Exit fullscreen mode

3. Timezone-Aware Cron Jobs – “Because your users don’t all live in the same city”

Real-life example:

You want a job to run every night at 2:00 AM IST, regardless of where the server is hosted (e.g., UTC).

This is why timezone support matters.

import { Cron } from '@nestjs/schedule';
import { Injectable } from '@nestjs/common';

@Injectable()
export class TaskService {
    @Cron('0 2 * * *', { timeZone: 'Asia/Kolkata', })
    handleCacheClear() {
        console.log('Cache cleared at 2:00 AM IST!');
    }
} 
Enter fullscreen mode Exit fullscreen mode

💡 By using the timeZone option, the job respects the correct local time for your users.

Tips for Cron in NestJS

  • Use @cron() for static tasks
  • Use SchedulerRegistry for dynamic job creation and management
  • Use timeZone to schedule accurately for different regions
  • Log job creation and execution for easier debugging
  • Clean up jobs after completion or when canceled

Final Thoughts

Cron jobs help bring automation and intelligence to your backend services. Whether you're building:

  • Blog scheduling systems
  • Auto-email reminders
  • Background cleanups
  • Periodic backups

NestJS makes all of this easy and maintainable with its @nestjs/schedule module.

So next time you hear "cron job", don’t just think about Linux terminals — think of digital alarms helping your app run smartly. ⏰💻

If you found this helpful and want more like this, drop a comment below or reach out to me!

Top comments (0)