Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use node-schedule to run a cron only on one instance?

My question is how to use node-schedule to run a cron only on one instance out of two instances of node server. Currently it is running on both instances but I want it to be executed only on one instance. So How can you make a cluster run a task only once? Thanks in advance.

{
  "apps": [
    {
      "name": "Example",
      "script": "boot/app/app.js",
      "watch": false,
      "exec_mode": "cluster_mode",
      "instances": 2,
      "merge_logs": true,
      "cwd": "/srv/www.example.com/server",
      "env": {
        "NODE_ENV": "development",
        .......
    .......
      }
    }
  ]
}
like image 597
Kamal K Avatar asked Nov 04 '16 12:11

Kamal K


People also ask

How do I schedule a node-cron?

To create our email scheduler application insert the following code into the index. js file: const express = require("express"); const cron = require("node-cron"); const nodemailer = require("nodemailer"); app = express(); //send email after 1 minute cron.

Can you set a single cron job to run once every second?

It's not possible to run cron in every second but we can run cron in every second using this method, we use a sleep command before the echo date. Cron - Cron is command name that runs scheduled action using the crond daemon.

What is the technique used to schedule jobs to specific nodes?

node-cron syntax It is a package used to schedule tasks (functions or commands) in Node. js. Its name is derived from the Greek word 'Chronos' meaning time. These tasks can be scheduled to either run once or repeatedly.


1 Answers

You can use an environment variable provided by PM2 itself called NODE_APP_INSTANCE which requires PM2 2.5.

NODE_APP_INSTANCE environment variable is used to determine difference between process, for example you may want to run a cronjob only on one process, you can just check if process.env.NODE_APP_INSTANCE === 0, Since two processes can never have the same number.

More Info on PM2 official doc here.

like image 168
Rahul Kumar Avatar answered Oct 27 '22 22:10

Rahul Kumar