Search code examples
cronfastify

the best way to run cron jobs with fastify


I had been using fastify-cron to run cron jobs with my fastify4 app. But, it seems the old fastify-cron plugin no longer is compatible with fastify5. What (if any) is the recommended way to run a fastify route periodically (once a day or once a week)?


Solution

  • You can use @fastify/schedule, a core Fastify plugin (meaning the Fastify team maintains it) that supports creating cron-style scheduling tasks.

    See the code example below for running a task that prints a message to the console every 5 seconds:

    import Fastify from "fastify";
    import { fastifySchedule } from "@fastify/schedule";
    import { CronJob, AsyncTask } from "toad-scheduler";
    
    const app = Fastify({
      logger: true,
    });
    
    const task = new AsyncTask("simple task", async (taskId) => {
      console.log(`this is ${taskId} that runs every 5 seconds`, Date.now());
    });
    
    const job = new CronJob(
      {
        cronExpression: "*/5 * * * * *", // Runs every 5 seconds
      },
      task
    );
    
    app.register(fastifySchedule);
    
    // `fastify.scheduler` becomes available after initialization.
    app.ready().then(() => {
      app.scheduler.addCronJob(job);
    });
    
    app.listen({ host: "0.0.0.0", port: 3000 });