Code Monkey home page Code Monkey logo

fastify-cron's Introduction

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.

fastify-cron's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar franky47 avatar gtolarc avatar robak08 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

fastify-cron's Issues

Error: plugin must be a function or a promise

Title says it all - I'm trying to register the plugin in the following way, as per the docs:

fastify.register(require('fastify-cron'), {
  jobs: [
    {
      cronTime: '50 * * * *',
      onTick: someFunction,
      startWhenReady: true
    }
  ]
})

Something went wrong. cron reached maximum iterations.

I let it do cron jobs per minute,so it throw a error that cron reached maximum iterations.
will it happens when i do cron jobs not so often?

D:\xxx\node_modules\cron\lib\cron.js:235
                                        throw new Error(
                                        ^

Error: Something went wrong. cron reached maximum iterations.
                                                Please open an  issue (https://github.com/kelektiv/node-cron/issues/new) and provide the following string
                                                Time Zone: "" - Cron String: 0 * * * * * - UTC offset: +08:00 - current Date: Tue Dec 08 2020 17:28:06 GMT+0800
    at CronTime._getNextDateFrom (D:\xxx\node_modules\cron\lib\cron.js:235:12)
    at CronTime.sendAt (D:\xxx\node_modules\cron\lib\cron.js:156:17)
    at CronTime.getTimeout (D:\xxx\node_modules\cron\lib\cron.js:175:29)
    at CronJob.start (D:\xxx\node_modules\cron\lib\cron.js:613:31)
    at Timeout.callbackWrapper [as _onTimeout] (D:\xxx\node_modules\cron\lib\cron.js:665:29)
    at listOnTimeout (node:internal/timers:556:17)
    at processTimers (node:internal/timers:499:7)
[nodemon] app crashed - waiting for file changes before starting...
^Cnpm ERR! path D:\xxx
npm ERR! command failed
npm ERR! signal SIGINT
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c "nodemon app/"

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\xxx\AppData\Local\npm-cache\_logs\2020-12-05T10_42_03_543Z-debug.log

is it bug?are there any ways to handle this problem?

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.