All Projects β†’ 47ng β†’ fastify-cron

47ng / fastify-cron

Licence: MIT license
Run cron jobs alongside your Fastify server πŸ‘·

Programming Languages

typescript
32286 projects
shell
77523 projects

Projects that are alternatives of or similar to fastify-cron

fastify-autoroutes
fastest way to map directories to URLs in fastify
Stars: ✭ 70 (+118.75%)
Mutual labels:  fastify, fastify-plugin
Wipe Modules
πŸ—‘οΈ Easily remove the node_modules folder of non-active projects
Stars: ✭ 304 (+850%)
Mutual labels:  cron, cron-jobs
mautic-cron-commands
Script to run Mautic commands from a web page.
Stars: ✭ 32 (+0%)
Mutual labels:  cron, cron-jobs
fastify-file-upload
Fastify plugin for uploading files
Stars: ✭ 68 (+112.5%)
Mutual labels:  fastify, fastify-plugin
Laravel Totem
Manage Your Laravel Schedule From A Web Dashboard
Stars: ✭ 1,299 (+3959.38%)
Mutual labels:  cron, cron-jobs
cronex
A cron like system built in Elixir, that you can mount in your supervision tree
Stars: ✭ 43 (+34.38%)
Mutual labels:  cron, cron-jobs
mi-cron
πŸ“† A microscopic parser for standard cron expressions.
Stars: ✭ 16 (-50%)
Mutual labels:  cron, cron-jobs
fastify-etag
Automatically generate etags for HTTP responses, for Fastify
Stars: ✭ 61 (+90.63%)
Mutual labels:  fastify, fastify-plugin
Tiktok
Python web visualize build on the awesome web framework sanic
Stars: ✭ 55 (+71.88%)
Mutual labels:  cron, cron-jobs
Chronos
Fault tolerant job scheduler for Mesos which handles dependencies and ISO8601 based schedules
Stars: ✭ 4,303 (+13346.88%)
Mutual labels:  cron, cron-jobs
fastify-openapi-glue
A plugin for Fastify to autogenerate a configuration based on a OpenApi(v2/v3) specification.
Stars: ✭ 94 (+193.75%)
Mutual labels:  fastify, fastify-plugin
Crontabmanager
PHP library for GNU/Linux cron jobs management.
Stars: ✭ 113 (+253.13%)
Mutual labels:  cron, cron-jobs
fastify-cors
Fastify CORS
Stars: ✭ 212 (+562.5%)
Mutual labels:  fastify, fastify-plugin
magento2-module-cron-schedule
A Magento2 visual cronjob overview for magento2 backend
Stars: ✭ 35 (+9.38%)
Mutual labels:  cron, cron-jobs
fastify-passport
Use passport strategies for authentication within a fastify application
Stars: ✭ 150 (+368.75%)
Mutual labels:  fastify, fastify-plugin
nodejs-cron-job-must-know
it is an example of running node.js script with every certain period(cron job)
Stars: ✭ 35 (+9.38%)
Mutual labels:  cron, cron-jobs
session
Session plugin for fastify
Stars: ✭ 52 (+62.5%)
Mutual labels:  fastify, fastify-plugin
create-fastify-app
An utility that help you to generate or add plugin to your Fastify project
Stars: ✭ 53 (+65.63%)
Mutual labels:  fastify, fastify-plugin
Healthchecks
A cron monitoring tool written in Python & Django
Stars: ✭ 4,297 (+13328.13%)
Mutual labels:  cron, cron-jobs
Cronscheduler.aspnetcore
Cron Scheduler for AspNetCore 2.x/3.x or DotNetCore 2.x/3.x Self-hosted
Stars: ✭ 100 (+212.5%)
Mutual labels:  cron, cron-jobs

fastify-cron

NPM MIT License Continuous Integration Coverage Status

Run 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.

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].