CRON + Nodejs + multiple cores => behavior?
I am creating a CRON module as my service (using node-schedule ) that will be needed in every instance of my multi-core setup and I am wondering since they all start their own threads, and they are all scheduled to run at the same time. whether they will be called for each separate thread, or just once, because they all load the same module.
If they are called multiple times, what is the best way to make sure the desired actions are called only once?
source to share
node-schedule
runs inside a given node process and it schedules what that particular node process has requested so that it schedules.
If you are using multiple node processes and each uses a node-schedule, then all instances of the node-schedule within those individual node processes are independent (there is no collaboration or coordination between them). If each node process requests its own node -schedule instance to run a specific task at 3pm in the first half of the month of the month, then all node processes will start running that task at that time.
If you only want one activity that you perform once, you need to coordinate between your node-instances so that the activity is scheduled in only one node process and not all of them, or only schedule these types of activity in one of your instances node, not all of them.
source to share
if you are using pm2 in cluster mode then you can use process.env.NODE_APP_INSTANCE to determine which instance is running. You can use the following code so that your cron jobs are only called once.
// run cron jobs only for first instance
if(process.env.NODE_APP_INSTANCE === '0'){
// cron jobs
}
source to share