Search code examples
javascriptnode.jscronserver-sideserverside-javascript

Running a NodeJS cron from cron-job.org


I am trying to run a NodeJS cron at a set interval using cron-job.org, but they don't have any documentation about how to actually run the script.

Basically the service visits a URL that you provide at a set interval, but I am specifically confused about what kind of code I can put on the endpoint (specifically what type of code will actually run). Can someone provide an example of what I would put at the endpoint URL?


Solution

  • You can do something really simple using either the HTTP module in Node.js or the popular Express module. Using express you can do something really simple like:

    var express = require('express');
    var app = express();
    
    app.get("/test", function(req, res, next){
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({ status: 'OK', timeStamp: new Date().toISOString() }));
    });
    
    console.log('Express listening.. on 3000');
    app.listen(3000);
    

    You can really run anything you like in the /test endpoint, though when it's being called from cron-job.org they'll probably stop if you keep throwing back 400 errors at them or the script takes really long to execute.

    You'd call this using the url

    http://yourdomain:3000/test
    

    And of course you might well want to change the port number and path!