npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fastify-cron

v1.3.1

Published

Run cron jobs alongside your Fastify server

Downloads

32,049

Readme

NPM MIT License Continuous Integration Coverage Status

While running cron jobs in the same process as a service is not the best recommended practice (according to the Twelve Factor App), it can be useful when prototyping and when implementing low-criticality features on single-instance services (remember that when scaling horizontally, all your jobs may run in parallel too, see Scaling).

There is an existing discussion about this in fastify/fastify#1312.

Installation

$ yarn add fastify-cron
# or
$ npm i fastify-cron

Usage

Register the plugin with your Fastify server, and define a list of jobs to be created:

If (like me) you always forget the syntax for cron times, check out crontab.guru.

import Fastify from 'fastify'

// Import it this way to benefit from TypeScript typings
import fastifyCron from 'fastify-cron'

const server = Fastify()

server.register(fastifyCron, {
  jobs: [
    {
      // Only these two properties are required,
      // the rest is from the node-cron API:
      // https://github.com/kelektiv/node-cron#api
      cronTime: '0 0 * * *', // Everyday at midnight UTC

      // Note: the callbacks (onTick & onComplete) take the server
      // as an argument, as opposed to nothing in the node-cron API:
      onTick: async server => {
        await server.db.runSomeCleanupTask()
      }
    }
  ]
})

server.listen(() => {
  // By default, jobs are not running at startup
  server.cron.startAllJobs()
})

You can create other jobs later with server.cron.createJob:

server.cron.createJob({
  // Same properties as above
  cronTime: '0 0 * * *', // Everyday at midnight UTC
  onTick: () => {}
})

To interact with your jobs during the lifetime of your server, you can give them names:

server.cron.createJob({
  name: 'foo',
  cronTime: '0 * * * *', // Every hour at X o'clock
  onTick: () => {}
})

// Later on, retrieve the job:
const fooJob = server.cron.getJobByName('foo')
fooJob.start()

Otherwise, you can access the list of jobs ordered by order of creation at server.cron.jobs.

Warning: if you mutate that list, you must take responsibility for manually shutting down the jobs you pull out.

Cron Jobs Lifecycle

Cron jobs can be created either by passing properties to the job option when registering the plugin, or when explicitly calling server.cron.createJob.

They are created by default in a stopped state, and are not automatically started (one good place to do so would be in a post-listening hook, but Fastify does not provide one).

Starting jobs

The recommended moment to start your jobs is when the server is listening (this way you can create test servers without cron jobs running around) :

const server = Fastify()

server.register(fastifyCron, {
  jobs: [
    // ...
  ]
})

server.listen(() => {
  server.cron.startAllJobs()
})

If you want to start a job immediately (synchronously) after its creation, set the start property to true (this is part of the cron API):

// When registering the plugin:
server.register(fastifyCron, {
  jobs: [
    {
      cronTime: '0 0 * * *',
      onTick: () => {},
      start: true // Start job immediately
    }
  ]
})

// You can also act directly on the job object being returned:
const job = server.cron.createJob({ cronTime: '0 0 * * *', onTick: () => {} })
job.start()

If your job callback needs the server to be ready (all plugins loaded), it can be inappropriate to start the job straight away. You can have it start automatically when the server is ready by settings the startWhenReady property to true:

server.register(fastifyCron, {
  jobs: [
    {
      name: 'foo',
      cronTime: '0 0 * * *',
      onTick: server => {
        server.db.doStruff()
      },
      startWhenReady: true
    }
  ]
})

Stopping jobs

Jobs are stopped automatically when the server stops, in an onClose hook.

If you have running cron jobs and need to stop them all (eg: in a test environment where the server is not listening):

test('some test', () => {
  // ...

  // Stop all cron jobs to let the test runner exit cleanly:
  server.cron.stopAllJobs()
})

Scaling

When horizontal-scaling your applications (running multiple identical instances in parallel), you'll probably want to make sure only one instance runs the cron tasks.

If you have a way to uniquely identify an instance (eg: a number passed in the environment), you could use that to only enable crons for this instance.

Example for Clever Cloud:

if (process.env.INSTANCE_NUMBER === 0) {
  server.register(fastifyCron, {
    jobs: [
      // ...
    ]
  })
}

Conditionally running jobs

You may want to run certain jobs in development only, or under other conditions.

fastify-cron will ignore any falsy values in the jobs array, so you can do:

server.register(fastifyCron, {
  jobs: [
    process.env.ENABLE_DEV_JOB === 'true' && {
      name: 'devJob',
      cronTime: '* * * * *',
      onTick: server => {
        // ...
      }
    }
  ]
})

Compatibility Notes

Some compatibility issues may arise with the cron API.

Possible issues (ticked if confirmed and unhandled):

  • [ ] Adding callbacks to a job via addCallback may not result in the server being passed as an argument
  • [ ] Using fireOnTick may lead to the same problem

License

MIT - Made with ❤️ by François Best

Using this package at work ? Sponsor me to help with support and maintenance.