Schedule Tasks in Node.js Using Node-cron

Imagine if you had to wake up every morning and manually send emails, clean up logs, or remind yourself to drink water. Sounds exhausting, right? Well, that’s where Node-cron comes in! It’s like your personal assistant that lets you schedule tasks in your Node.js applications.

Why Use Node-cron?
Instead of running tasks manually, Node-cron lets you automate them, saving time and reducing errors.
1)Automated Backups – Schedule database backups at set intervals.
2)Email Notifications – Send periodic emails to users.
3)Data Scraping – Fetch real-time data from external sources.
4)Log Cleanup – Delete old logs to free up space.

Scheduling Tasks with Node-cron

The cron.schedule()  function lets you define when tasks should run.

Example 1: Running a Task Every Minute

const cron = require("node-cron");

// Run a task every minute
cron.schedule("* * * * *", () => {
    console.log("Task executed at:", new Date().toLocaleTimeString());
});

Explanation:

  • * * * * * → Runs the task every minute.

  • Prints the current time when executed.

OUTPUT :

Task executed at: 10:30:00 AM
Task executed at: 10:31:00 AM
Task executed at: 10:32:00 AM
...

Example 2: Sending Emails Daily at Specific Time

 

const cron = require("node-cron");
const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: { user: "[email protected]", pass: "your-password" }
});

// Schedule an email every day at 9 AM
cron.schedule("0 9 * * *", () => {
    transporter.sendMail({
        from: "[email protected]",
        to: "[email protected]",
        subject: "Daily Update",
        text: "This is your scheduled email!"
    }, (error, info) => {
        if (error) console.log("Error:", error);
        else console.log("Email sent:", info

What’s Happening Here?

1)0 9 * * * → Runs every day at 9 AM. Perfect for sending daily inspiration (or passive-aggressive reminders).

2)Uses Nodemailer to send an email (because texting is so much work).

OUTPUT(if everything goes fine):

Email sent: 250 OK: Message accepted

If it fails, you might see:

Uh-oh! Error: SMTP Authentication failed

(Yes, that means you probably typed your password wrong.)

Conclusion: 

With node-cron, you can automate boring, repetitive tasks and focus on what truly matters.Whether it’s sending emails, cleaning up log files, scheduling backups, or scraping data, this tool has your back.

With node-cron, you can automate repetitive tasks and let your app handle the workload while you focus on more important things. Pair it with tools like Nodemailer, databases, or APIs to build a smarter, more efficient system that runs seamlessly in the background. You can also further refer to these below:

🔗 Node-cron Official Docs
🔗 Cron Job Expressions Explained
🔗 Nodemailer for Sending Emails

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top