Fastify Cron Job for Scheduling Tasks Monthly, Daily

This blog post dives into the world of Fastify cron jobs, equipping you with the knowledge and code to schedule tasks and automate actions within your Fastify application. We’ll cover what cron jobs are, how to leverage them in Fastify, and explore practical examples like triggering actions at the start of each month.

What is a Cron Job in Fastify?

Cron, short for “chronic,” is a task-scheduling utility found in Linux and Unix-based systems. Fastify, a popular Node.js web framework, can integrate with cron-like functionality to automate tasks within your application at specific intervals. This empowers you to trigger actions periodically, in the background, without requiring user interaction.

Triggering Actions at Month Start

A common use case for Fastify cron jobs involves executing tasks at the beginning of each month. This could involve generating reports, sending automated emails, or performing database maintenance. By leveraging cron expressions, you can define the exact timing for these actions.

For instance, the cron expression 0 0 1 * * translates to “run at minute 0, hour 0, on the 1st day of the month, every month.” This ensures your desired task executes precisely at midnight on the first day of each month.

Fastify Cron Job Example Code – Month Start Autorun

Before we embark on creating cron jobs within your Fastify application, we’ll need to equip it with the necessary scheduling capabilities. Here’s where fastify-cron comes in. This handy package acts as a bridge between Fastify and the world of cron scheduling. To install it, navigate to your project’s terminal and run the following command:

npm install fastify-cron --save

This command fetches the fastify-cron package from the npm registry and adds it as a dependency to your project. With fastify-cron in place, you’ll be ready to leverage cron expressions and schedule tasks seamlessly within your Fastify application.

import fastifyCron from "fastify-cron";

const server = Fastify();

server.register(fastifyCron, {
  jobs: [
    {
      cronTime: "0 0 1 * *", // This cron expression means "at 00:00 on day-of-month 1"
      onTick: async () => {
        try {
          await resetMonthlyCounts();   //call ur custom function to be executed
          console.log("Monthly Stats reset successfully");
        } catch (error) {
          console.error("Failed to reset monthly counts:", error);
        }
      },
      start: true, // Start the job immediately
      timeZone: "Asia/Kolkata", // UTC India

      // timeZone: 'UTC', // Specify the timezone if necessary
      // cronTime: '* * * * *', // Every minute - for testing purpose
    },
  ],
});

 server
    .listen({
      port: port,
      host: host,
    })
    .then(() => {
      console.log(`Server ready at ${port}`);
      server.cron.startAllJobs();  
    })
    .catch((e) => {
      console.error(e);
      process.exit(1);
 });
how to create a cron job in fastify

Conclusion

Fastify cron jobs offer a powerful mechanism to automate tasks and enhance the functionality of your web application. By incorporating the concepts and code examples presented in this blog post, you’ll be well-equipped to implement background jobs and scheduled actions within your Fastify projects. Stay tuned for future posts where we’ll delve deeper into specific use cases and explore best practices for managing Fastify cron jobs effectively.

About the Author: smartcoder

You might like

Leave a Reply

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