I need to get a stock price from an API and save it to the database every 15min whats the best way to do this?
My first thought was to use node-fetch with a setInterval but I'm not sure this is best practice. Or maybe a cron job with node-cron?
node-cron can work, but you will lose the scheduled tasks if the server goes down. I have used schedulers like agenda extensively in the past and benefits from having a persistence layer.
For example:
agenda.define('getStockPrice', async job => { const data = await stockeService.getPrice(); ... }); agenda.every('15 minutes', 'getStockPrice'); Checkout the docs for more info.
setInterval() in the startup code when your server restarts too. I'm just trying to understand what's the advantage of using an external package for such a simple problem. This isn't dozens of scheduled tasks at all various times. It's just one recurring polling operation.Use cron job https://www.npmjs.com/package/node-cron
It's a best way to run the api or any function every time which we want to.
The node-cron module is tiny task scheduler in pure JavaScript for node.js based on GNU crontab. This module allows you to schedule task in node.js using full crontab syntax.
setInterval()?
setInterval()and therequest-promiselibrary for making the http request is one option.