Automating Tasks with Cron Jobs and NestJs.
A Deep Dive into Task Scheduling with NestJS.

Full Stack Developer | Node.js, MongoDB, PostgreSQL, Docker, AWS | Exploring AI, Workflow Automation & AI Agents | Sharing backend tips, dev tools & learning in public 🚀
Nowadays, web applications effortlessly handle user-initiated tasks through Cron and task scheduling. Users can specify the exact time for their desired action with a simple click. Moreover, the convenience extends to recurring tasks, eliminating the need for repeated button clicks by seamlessly automating requests to the server.
For example, consider you want to share a cool pic on social media, but you also want to sleep in. Enter Cron, your virtual timekeeper.
You pick a date and time for your post, hit 'schedule,' and that's it. Cron takes over from there. It checks the clock every so often, like a friendly reminder. When the magic moment arrives, Cron high-fives your post into the social media world, all without you lifting a finger.
It's like having a super reliable friend who never forgets to share your stuff exactly when you want. No alarms, no late-night post-clicking—just easy, breezy posting. Thanks, Cron, for being the ultimate sidekick in our social media adventures! 🌟
Well, It comes from the Linux world, and this is often handled by packages like cron at the OS level.
To start using it, we first install the required dependencies.
$ npm install --save @nestjs/schedule
With cron operators, you can define the time to execute jobs. Some of these operators include:
Asterisks (*)
Comma (,)
Hyphen (-)
Slash (/)
The All-Powerful Asterisk:
When you see all asterisks ( * * * * * ), it means Cron is saying, "I got this!" Your job will run every minute, every hour, every day of the month, every month, and every day of the week. It's like setting things on autopilot.
The format of a asterisks is given as : second minute hour day(month) month day(week)
In simple terms, * * 5 * 3 means your task is like setting an alarm to do something every second, every minute, and every hour, but only on Wednesdays that fall on the 5th day of the month. It's like a super specific reminder that kicks in at that particular time! 🕰️📆
Syntax and Semantics of Slash:
Ever felt like your Cron jobs could use a touch of simplicity? Say hello to slashes! Unlocking the Slash:
Let's spice up your typical cron, like '* * 5 \ 3 '. Now, throw in a slash for the minutes: ' **/15 * * * * '.
What's */15?
It's the secret sauce, meaning "Do this every 15 minutes." Simple, right?
Do you have a task every 10 minutes? Easy peasy—write it as '' \/10 \ * * * ". Suddenly, your task is a breeze, happening every 10 minutes like clockwork.
So Let's Understand and go practical by Diving into Cron Simple Social Media Automation with NestJS.
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
@Injectable()
export class CronjobsService {
@Cron('0 * * * * *')
postToSocialMedia() {
console.log("New social media post is live!");
// Add logic here to create and publish a new social media post.
}
@Cron('*/5 * * * * *')
continuePosting() {
console.log("Still active on social media, posting updates!");
// Add logic here to create and publish additional social media posts.
}
}
Now Let's Understand the above code snippet
postToSocialMedia, shouts, "New post!" every minute, creating and publishing a fresh social media update. Continue posting, Every 5 seconds, it's like a busy bee, buzzing with more posts to keep your social media game lively.
Well, now it is time to go on some advanced Custom Post Deactivation System using NestJs.
@Cron('45 * * * * *')
async getPosts() {
const date_obj = Date.now();
const Postsdata = await this.postModel.findOne({
scheduleDateAndTime: { $gt: date_obj - 300000, $lt: date_obj + 300000 },
isActive: true,
});
if (Postsdata != null) {
const result = await this.postModel.findOneAndUpdate(
{ email: Postsdata.email },
{ isActive: false },
{ new: true },
);
console.log('Post deactivated and updated successfully.');
}
}
In this NestJS Cron running every 45 seconds, we use Date.now() to grab the current time. It's a JavaScript trick giving us the time in milliseconds. This timestamp guides the code to fetch posts scheduled within the last and next 5 minutes, ensuring they're active. We can also use it by Date Object. If found, the code smoothly deactivates these posts, logging a simple success message, "Post deactivated and updated successfully." This showcases NestJS Cron's efficiency in handling post management with precision. 🕒
Ever wondered what happens behind the curtain of my post-management system? Here's a sneak peek. When I'm posting data into the Posts Schema, I do something with the scheduled time.
Using const date = new Date(createPostDto.scheduleDateAndTime).getTime(); I turn the scheduled date and time into milliseconds. It's like creating a time stamp for each post. Why? Because it lets me easily do things with posts scheduled within the last and next 5 minutes. This little trick ensures that managing schedules with precision in my NestJS application is as smooth as can be.
Take a peek at my post schema.

For a comprehensive view of the complete code and to explore the intricacies further, feel free to visit the GitHub repository here. This provides a hands-on opportunity to delve into the codebase and understand the implementation details behind this user-centric approach to post management in NestJS. ⏰🌟.


