
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
fastify-cron
Advanced tools
fastify-cronRun cron jobs alongside your Fastify server.
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.
$ yarn add fastify-cron
# or
$ npm i fastify-cron
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 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).
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
}
]
})
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()
})
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: [
// ...
]
})
}
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 => {
// ...
}
}
]
})
Some compatibility issues may arise with the cron API.
Possible issues (ticked if confirmed and unhandled):
addCallback may not result in the server being passed as an argumentfireOnTick may lead to the same problemMIT - Made with ❤️ by François Best
Using this package at work ? Sponsor me to help with support and maintenance.
FAQs
Run cron jobs alongside your Fastify server
The npm package fastify-cron receives a total of 4,534 weekly downloads. As such, fastify-cron popularity was classified as popular.
We found that fastify-cron demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.