How to Exit Your Background Process that Takes Too Long to Run using NodeJs?


I have a long running application that I configure it in cronjob to run every 12 minutes. As it listens to the blockchain for transactions, sometimes it takes more than 12 minutes to run, and sometimes it even hangs due to network problems. When I search the processes by name and I can see from time to time the processes pile up in task manager e.g. htop.

I come up with the following approach to exit the process if it takes more than a threshold.

Let’s give it 5 minute to run:

1
2
3
const config = {
  "max_running_time": 300 // 5 minutes
};
const config = {
  "max_running_time": 300 // 5 minutes
};

Then, we need to define a function to check if time has passed:

1
2
3
4
5
6
7
8
// global - remembers when we started the application
const START_TIME = new Date();
console.log("Start Running at Time: ", START_TIME);
 
function isRunningLongerThan(seconds) {
    const sec = (new Date() - START_TIME)/1000;
    return sec >= seconds; 
}
// global - remembers when we started the application
const START_TIME = new Date();
console.log("Start Running at Time: ", START_TIME);

function isRunningLongerThan(seconds) {
    const sec = (new Date() - START_TIME)/1000;
    return sec >= seconds; 
}

That is it. In your long running loop make sure add the check:

1
2
3
4
5
6
7
8
function longRunning(config) {
    while (workNotDone()) {
       if (isRunningLongerThan(config.max_running_time)) {
           console.err("Taking too much time - exiting..");
           process.exit(1);
       }
    }
}
function longRunning(config) {
    while (workNotDone()) {
       if (isRunningLongerThan(config.max_running_time)) {
           console.err("Taking too much time - exiting..");
           process.exit(1);
       }
    }
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
285 words
Last Post: How to Truncate a String in PHP?
Next Post: Teaching Kids Programming - Sudoku Validator/Algorithm using 27 Hash Sets

The Permanent URL is: How to Exit Your Background Process that Takes Too Long to Run using NodeJs?

Leave a Reply