DEV Community

Cover image for Automating the Mundane: My Journey with Node-cron
Aminah Rashid
Aminah Rashid

Posted on

Automating the Mundane: My Journey with Node-cron

Have you ever had that bad feeling of having forgotten something important? Imagine that "something" to be remembering to mark one's daily attendance at work. While developing an attendance management system, this exact scenario posed a considerable problem: How could I ensure that users log in their presence consistently when they forgot to do so? This led me to explore automated solutions, ultimately discovering Node-cron as an effective tool for scheduling tasks in Node.js applications..

The Problem
Imagine this: a brand-new attendance system, shiny, ready to check in and out every user. The trouble was that it relied on people to remember to use it. Anyone who has ever forgotten their keys can testify that human memory is not always the most reliable thing in the world. I needed some surefire method whereby these attendance records would be verified and updated automatically so that our digital tracker wouldn't stray when people forgot or occasionally tried to take advantage of it.

Learning Approach And Solution Steps
To address this challenge, I began with online research, using resources like developer forums and documentation. When Node-cron was suggested as a potential solution, I adopted a structured learning approach:

Node-cron: The Scheduling Master
Let me introduce you to basis of Node-cron, the unsung hero of task automation in the Node.js world.You can think of it as a super-smart alarm clock for your code. Using cron expressions—a series of five fields representing minutes, hours, days, months, and weekdays—you will tell your application strictly when it should execute specific functions.

Image description

For instance, "0 19 * * *" will mean "Execute this task every day at precisely 7:00 PM!" It is like an assistant who will never stop or forget to do his job.

Node-cron Basics
The following are some code snippets that will give users a feel for what Node-cron can do:

Daily Task at a Specific Time
const cron = require('node-cron');

cron.schedule("0 19 * * *", () => {
  console.log("This task runs at 7:00 PM every day!");
});

Hourly Task
cron.schedule("0 * * * *", () => {
  console.log("This task runs at the start of every hour.");
});

Weekly Task on Mondays
cron.schedule("0 9 * * 1", () => {
  console.log("This task runs every Monday at 9:00 AM.");
});

Monthly Task on the First Day
cron.schedule("0 0 1 * *", () => {
  console.log("This task runs on the first day of every month at midnight.");
});
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate Node-cron's adaptability, handling everything from daily reminders to monthly updates. But how exactly did it tackle our attendance challenge?

The Attendance Automation Solution
Get ready for the game-changer - the code that revolutionized our attendance system from prone to forgetfulness to completely reliable:

cron.schedule("0 19 * * *", async () => {
  try {
    const users = await User.find();
    for (const user of users) {
      const existingAttendance = await Attendance.findOne({
        userId: user._id,
        createdAt: { $gte: new Date().setHours(0, 0, 0, 0) },
      });
      if (!existingAttendance) {
        await Attendance.create({
          userId: user._id,
          status: "Absent",
        });
      }
    }
    console.log("Attendance records updated.");
  } catch (error) {
    console.error("Error updating attendance records:", error);
  }
});
Enter fullscreen mode Exit fullscreen mode

The following code will automate the daily attendance checks: fetch all users from the database, check attendance against already available records for the given day, and create new "Absent" records for users who have not marked it. It also flashes a success update message and logs errors encountered during this process for debugging and maintenance. This approach dramatically increases the reliability of an attendance management system by ensuring proper tracking without manual oversight.

Grow Your Skills At HNG Internship
Implementing Node-cron to solve our attendance challenge proved the power of automation in backend development. As a full-stack developer coming from the frontend, I've learned and valued the complexity and importance that server-side solutions bring.

This experience aligns perfectly with the HNG Internship's practical approach. While HNG offers various tracks, it's particularly valuable for aspiring backend developers. If you're looking to work on real-world projects and expand your skills, this internship is an excellent opportunity.

My journey with HNG is driven by two goals: gaining hands-on experience with industry-level problems and expanding my international network. Whether you're passionate about Node.js, databases, or APIs, HNG provides a platform to grow, collaborate, and prepare for the tech industry's demands.

Want to better your backend and raise a hullabaloo by starting your career? Then, the HNG Internship definitely could be that giant step. It's not just about coding; it's about becoming a well-rounded developer ready for real-world challenges.

Final Thoughts
And there you have it—my tale of Node-cron, which came in to save the attendance system from human negligence. For developers navigating the complexities of scheduling tasks, Node-cron is a game-changer I wholeheartedly endorse. It's like having a mindful assistant on your code: attentive, efficient, and never late.

In the realm of software development, the most invaluable solutions often operate silently, ensuring seamless operations behind the scenes. Here's to seamless coding experiences ahead!

Links:
Check out these Links, if you wanna learn more about HNG:

  1. HNG Internship
  2. HNG Premium

Top comments (1)