
Development
Cron Jobs in NestJS: A Simple Guide
What is a Cron Job?
A cron job is a task that runs on its own, again and again, at a fixed time. You do not need to click a button. The computer does the work for you.
Think about your daily life. Every morning, your alarm rings at 7 AM. You did not press it. It just knows the time and rings on its own. A cron job works the same way for computers. It “wakes up” at a set time and does a task.
Some real-life examples:
- Your phone backs up your photos every night at 2 AM.
- A bank sends you a monthly statement on the 1st of every month.
- A water purifier reminds you to change the filter every 3 months.
- A gym app sends a reminder every Monday to renew your membership.
All these are “cron jobs” in real life. Someone set a rule once, and now it repeats forever without extra effort.
Why Do We Need Cron Jobs in Software?
In software, we use cron jobs for tasks like:
- Sending daily reminder emails to users.
- Cleaning up old, unused files every night.
- Generating a sales report every week.
- Checking for expired subscriptions every day.
- Refreshing cached data every hour.
These tasks are repetitive. Doing them by hand is boring and can lead to mistakes. A cron job removes that human effort.
How Cron Jobs Work
A cron job uses a “cron expression” to decide when to run. It looks like this:
* * * * *
Each * stands for a time unit:
- Minute (0–59)
- Hour (0–23)
- Day of the month (1–31)
- Month (1–12)
- Day of the week (0–7, where 0 and 7 are Sunday)
For example:
0 7 * * *means “run every day at 7 AM.”0 0 1 * *means “run at midnight on the 1st of every month.”0 9 * * 1means “run every Monday at 9 AM.”
This is just like setting a repeat alarm on your phone.
Using Cron Jobs in NestJS
NestJS is a popular framework for building backend applications with Node.js. It has a simple way to add cron jobs using a package called @nestjs/schedule.
Step 1: Install the Package
npm install --save @nestjs/schedule
Step 2: Import the Module
Open your app.module.ts file and add ScheduleModule:
import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
This tells your app: “Get ready, we will run some scheduled tasks.”
Step 3: Create a Service with a Cron Job
Now create a service file, for example tasks.service.ts:
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
@Injectable()
export class TasksService {
private readonly logger = new Logger(TasksService.name);
@Cron(CronExpression.EVERY_DAY_AT_7AM)
handleMorningReminder() {
this.logger.log('Good morning! Sending daily reminders now.');
// your logic here, like sending emails
}
}
Here, @Cron() is a decorator. It tells NestJS: “Run this function automatically at 7 AM every day.” This is just like setting your morning alarm, but for code.
You can also write your own custom time pattern:
@Cron('0 0 * * *') // runs every midnight
handleMidnightCleanup() {
this.logger.log('Cleaning up old files...');
}
Step 4: Add the Service to Your Module
import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
@Module({
providers: [TasksService],
})
export class TasksModule {}
That’s it. Your cron job is now live inside your app.
Everyday Life Example Mapped to Code
Real-Life Example NestJS Cron Job Alarm rings every day at 7 AM @Cron(CronExpression.EVERY_DAY_AT_7AM) Rent reminder on 1st of month @Cron('0 0 1 * *') Weekly grocery list every Sunday @Cron('0 10 * * 0') Watering plants every 3 hours @Cron('0 */3 * * *')
Once you understand your daily routine, cron expressions start to feel very natural.
How to Deploy a NestJS App with Cron Jobs
Once your cron job works on your laptop, you need to put it on a server so it keeps running all the time, even when your laptop is off. This is called deployment.
Here are simple steps to deploy it:
1. Build Your Application
First, turn your TypeScript code into plain JavaScript, which servers can run:
npm run build
2. Choose a Hosting Option
You can deploy your NestJS app on platforms like:
- VPS (Virtual Private Server), like DigitalOcean or AWS EC2
- Platform as a Service, like Render, Railway, or Heroku
- Containers, using Docker and Kubernetes
3. Keep the App Running Always
A cron job only works if your app is always running. On a normal computer, the app stops when you close the terminal. On a server, we use tools to keep it alive:
- PM2: A process manager that restarts your app if it crashes.
npm install -g pm2
pm2 start dist/main.js --name my-app
- Docker: Package your app in a container so it runs the same way everywhere.
- Systemd: A Linux tool to keep services running in the background.
4. Watch Out for Multiple Instances
If you deploy your app on more than one server (for scaling), your cron job might run multiple times at the same moment. This can cause duplicate emails or duplicate reports.
To avoid this, you can:
- Run cron jobs only on one dedicated instance.
- Use a distributed lock, like Redis, so only one server runs the job at a time.
- Use a separate worker service just for scheduled tasks, apart from your main app.
5. Set the Correct Time Zone
Your server might be in a different time zone than your users. Always set the time zone clearly:
@Cron(CronExpression.EVERY_DAY_AT_7AM, {
timeZone: 'Asia/Kolkata',
})
handleMorningReminder() {
this.logger.log('Sending reminder in Indian time zone.');
}
This is like setting your alarm clock to your local time, not someone else’s.
6. Monitor Your Cron Jobs
After deployment, keep an eye on your jobs. Use logging tools or services like:
- Application logs (console or file-based)
- Monitoring tools like Sentry or Datadog
- Simple alerts if a job fails to run
Conclusion
A cron job is like a personal assistant for your app. It remembers to do repeated tasks, right on time, without anyone pushing a button. Just like your morning alarm or your monthly bill reminder, a cron job quietly works in the background.
In NestJS, setting up a cron job is easy with the @nestjs/schedule package. But remember, writing the code is just one part. Deploying it correctly, keeping it always running, and avoiding duplicate runs are just as important.
Once you get this right, your app will handle repeated tasks smoothly, just like a well-trained assistant who never forgets.

