最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Best way to call periodically (twice a day) an API from Node.js to get data - Stack Overflow

programmeradmin7浏览0评论

I've got my Node.js application which use the Fixer.io API to get some data. Currently the call is made when I reach the URL myapp/rate. My goal is to make this call automatically twice a day to store the data in my MongoDB database.

So I would like to know what is the best way to do that ? Maybe the setInterval() is the only way to do it but I don't think so...

My call looks like this :

router.get('/', (req, res, next) => {
  fixer.latest({ base: 'EUR', symbols: ['CAD'] })
    .then((data) => {
      var currentData = data.rates;
      if (currentData) {
        const currentRate = new Rate({ rate: currentData.CAD });
        currentRate.save((err) => {
          if (err) {
            throw err;
          } else {
            console.log('Data saved successfully!');
          }
        });
      }
    })
    .then(() => {
      Rate.find({}, { rate: 1, _id: 0 }, (err, rates) => {
        if (err) {
          throw err;
        } else {
          res.json(rates);
        }
      });
    })
    .catch(() => {
      console.log('Error');
    });
});

Thank's

I've got my Node.js application which use the Fixer.io API to get some data. Currently the call is made when I reach the URL myapp/rate. My goal is to make this call automatically twice a day to store the data in my MongoDB database.

So I would like to know what is the best way to do that ? Maybe the setInterval() is the only way to do it but I don't think so...

My call looks like this :

router.get('/', (req, res, next) => {
  fixer.latest({ base: 'EUR', symbols: ['CAD'] })
    .then((data) => {
      var currentData = data.rates;
      if (currentData) {
        const currentRate = new Rate({ rate: currentData.CAD });
        currentRate.save((err) => {
          if (err) {
            throw err;
          } else {
            console.log('Data saved successfully!');
          }
        });
      }
    })
    .then(() => {
      Rate.find({}, { rate: 1, _id: 0 }, (err, rates) => {
        if (err) {
          throw err;
        } else {
          res.json(rates);
        }
      });
    })
    .catch(() => {
      console.log('Error');
    });
});

Thank's

Share Improve this question asked Feb 28, 2017 at 21:15 HugoHugo 1634 silver badges16 bronze badges 2
  • The best way to automate a script to run at a particular time is to use cronjobs. Do you have access to them? – Obsidian Age Commented Feb 28, 2017 at 21:17
  • @ObsidianAge Sure I can do this with cronjobs but I would like to know if there is an other way juste in my code application ? – Hugo Commented Feb 28, 2017 at 21:28
Add a ment  | 

2 Answers 2

Reset to default 5

You can use the node module node-schedule to run a task within your node app on a cron-like schedule.

var schedule = require('node-schedule');

var j = schedule.scheduleJob('0 0 0,12 * *', function(){
  console.log('This will run twice per day, midnight, and midday');
});

The key word in your question is 'automatically'. The easiest (and most reliable) way to run a script at a particular time of day on the server would be to use cronjobs on the server. That way your server will execute the script regardless of the user interaction:

0   0   *   *   *   TheCommand // 12 a.m.
0   12   *   *   *   TheCommand //  12 p.m.

However, it is also possible to run a script at a particular time of day using a JavaScript setTimeout() as you were thinking. You need to calculate the current time, the target time, and the difference between them:

var now = new Date();
var payload = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 0, 0, 0) - now;
if (payload < 0) {
     payload += 46400000; // Try again 12 hours later
}
setTimeout(function(){ // YOUR DESIRED FUNCTION }, payload);

Note the 12 above in payload is the hour at which you want the script to run. In this example, I'm running the script at both 12 p.m. and 12 a.m.

Keep in mind that this will only work if the application is permanently running the page where the JavaScript is loaded; there's no way of forcing JavaScript to run 'in the background' as it is a client-side language.

Hope this helps! :)

发布评论

评论列表(0)

  1. 暂无评论