Subscribe to our list to receive the latest updates on Node on Fire

Class: Schedulers

Schedulers

new Schedulers(app)

The schedulers module. This module allows you to execute tasks during a cron-like time pattern. If you want to execute tasks after a certain action, have a look at the Triggers module instead. If you need actions to be executed real time (after a given action), consider executing workers in your model hooks instead.

To create a scheduler which runs every minute:

function ReportsScheduler() {
    // Runs every minute at 0 seconds.
    this.timingPattern = '0 * * * * *';
}
app.scheduler(ReportsScheduler);

ReportsScheduler.prototype.run = function() {
    // Do something. Make sure to return a promise.
}

The timingPattern allows you to set when to run your scheduler exactly. The format is cron-like except that you can specify the seconds as well. You can set 6 different values in the pattern each separated with a space in the following order:

  1. Seconds: 0-59
  2. Minutes: 0-59
  3. Hours: 0-23
  4. Day of Month: 1-31
  5. Months: 0-11
  6. Day of Week: 0-6

The * character indicates a wildcard and matches everything. For example, to run a scheduler:

  • every minute on the 30th second: 30 * * * * *.
  • every hour: 0 0 * * * *
  • every hour every day in January: 0 0 * * 1 *

You can also use a range.

  • every weekday at 11:30 AM: 0 30 11 * * 1-5

To read about more advanced patterns have a look at https://github.com/ncb000gt/node-cron and http://crontab.org.

Internally the schedulers module uses the Clock module, which guarantees your schedulers are run, even if your server processes crash right before the task should be scheduled and the processes start again right after the processes should've been scheduled. If multiple tasks were skipped, only one task is run. For example, you have a scheduler to run every hour, and your server crashes and is down for 4 hours. When your server, and Node on Fire, start again, your scheduler will notice it skipped several runs. It will run once after the crash, but not 4 times. This is considered a feature.

You can store your schedulers in the schedulers/ folder which will automatically load.

Tip: set the TZ environment variable to be explicit about the time zone to use. It's generally a good idea to align this setting with whatever your datastore is configured to.

For your schedulers to run, Node on Fire creates a worker process in the Procfile. This should happen automatically.

worker: node index.js --schedulers

Also a clock process is created. This is the process which times tasks and schedules work at the right time. The clock process is managed by the Clock module.

clock: node index.js --clock
Parameters:
Name Type Description
app App

The app.

Do you have any questions or comments on this page? Start a discussion below.

comments powered by Disqus
Subscribe to our list to receive the latest updates on Node on Fire