James
James

Reputation: 607

How to gracefully stop an Azure WebJob written for Nodejs

I'm aware that using the a setting.job file one can gracefully shutdown an Azure WebJob. This is my file:

    {
      "schedule": "0 */10 * * * *",
      "stopping_wait_time": 120
    }

I had written a WebJob in javascript. The WebJob runs on Nodejs. It is configured as on demand and triggered every 10 minutes by the setting.job. For some reason my setting.job file does not shutdown the WebJob gracefully. It always end failed.

Maybe I'm missing something or not understand completely how the shutdown of a WebJob ends but I ended with a nasty tweak in the run.js:

    setTimeout(function () {
        process.exit();
    }, 30000);

The piece of code is executed at the end of the script. I would like to know if there is a more elegant solution beside the one that I'm using.

run.js example:

    const http = require('http');
    const request = require('request');
    const fb = require('firebase');

    request(process.env.SourceUrl, function (error, response, body) {
        'use strict';
            if (!error && response.statusCode == 200) {
                // Process data from body
            } else {
                console.log(error);
            }
    });

    // Nasty hack to end gracefully
    setTimeout(function () {
       process.exit();
    }, 6000);

Upvotes: 1

Views: 600

Answers (2)

Peter Pan
Peter Pan

Reputation: 24138

I think the graceful way is waiting for the job done completely, not break off in processing.

const http = require('http');
const request = require('request');
const fb = require('firebase');

var sig = -1;

request(process.env.SourceUrl, function (error, response, body) {
    'use strict';
        if (!error && response.statusCode == 200) {
            // Process data from body

            sig = 0;
        } else {
            console.log(error);
            sig = 1;
        }
});

setInterval(function() {
    if(sig > -1) {
        process.exit(sig);
    }
}, 6000);

Upvotes: 1

Chris Anderson
Chris Anderson

Reputation: 8515

The cleaner way achieve your goal is to call process.exit after you've finished your business logic. This gives you full control over the lifecycle of your WebJob.

const http = require('http');
const request = require('request');
const fb = require('firebase');

request(process.env.SourceUrl, function (error, response, body) {
    'use strict';
        if (!error && response.statusCode == 200) {
            // Process data from body

            //When finished
            process.exit(0);
        } else {
            console.log(error);
            process.exit(1); // provide a non-zero error, because the job failed
        }
});

Upvotes: 0

Related Questions