Search code examples
javascriptnode.jssails.jsnode-cron

How to check how much time node-cron is taking for executing cron-job


I want to check how much time cron job is taking to execute the cron job process for that particular cron job.

After which if cron-job is taking more than 10 minutes to execute that process then that particular cron-job should be stopped and rest cron job should process as normal.

I am using node-cron package for cron job.

In below code I want to get how much time it takes to executes that process if it it is more than 10 minutes then in setTimeout() function i can use task.stop() method of cron to stop that cron job.

var task = cron.schedule('0 1 * * *', () => { console.log('Runing a job at 01:00') }


Solution

  • If I understand you correctly, you want to set a timeout to cancel a process if it exceeds 10 minutes of runtime. The best answer would depend on what kind of activity the process is doing. If you are using the child_process module to spawn another process you can start with an example from the documentation which kills the child process after 2 seconds and adjust it to your needs:

    'use strict';
    const { spawn } = require('child_process');
    
    const subprocess = spawn(
      'sh',
      [
        '-c',
        `node -e "setInterval(() => {
          console.log(process.pid, 'is alive')
        }, 500);"`
      ], {
        stdio: ['inherit', 'inherit', 'inherit']
      }
    );
    
    setTimeout(() => {
      subprocess.kill(); // Does not terminate the Node.js process in the shell.
    }, 2000);