The Bassman
The Bassman

Reputation: 2361

Using node CRON job to call own request

I have the following snippet:

const express = require('express')
const app = express()
const cronJob = require('cron').CronJob

app.get('/test', (req, res) => {
    // Do something here
}

new cronJob('* * * * * *', () => {
    // Call localhost:3000/test here
}, null, true, 'Asia/Manila')

app.listen(3000, () => console.log('Successfully listened to app 3000'))

Usually on node, localhost:3000/test runs if this is called on the browser right? I wanted to make the CRON run this without typing it on the browser once the node app starts. If possible also regardless of the hostname, whether it's localhost or not, the CRON should make the request without being typed on the browser. Can this be done?

Upvotes: 2

Views: 2679

Answers (1)

Tzook Bar Noy
Tzook Bar Noy

Reputation: 11677

I read the comments above on the questions itself and decided to add my thoughts even thought it seems like you got a solution.

In my opinion it will be much more clean for you to call the "method" itself instead of hitting "http" for getting the response you need.

You have 2 options:

  • Hitting the "domain.com/test" endpoint with a request call.
  • Simply calling the same method the above url is doing. In this way, you will "save" the overhead of need to "set-up" a new request to the express app with response and request headers. (example below)

let's say this is your code:

const handleTestData = () => return 'something';

app.get('/test', (req, res) => {
    const result = handleTestData();
    res.send(result);
}

new cronJob('* * * * * *', () => {
    // instead of calling http and getting the response
    // and adding overhead, just call the function
    const result = handleTestData();
    // do what you need with the result
}, null, true, 'Asia/Manila')

Upvotes: 2

Related Questions