How we can schedule a post request in node.js,so that the data get printed on website in every 24 hours. Or any given schedule time,the data should be printed.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people's questions, and connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
You can use node-cron. Firstly you need to run npm i node-cron to install.
To register a task all you have to do is:
const cron = require(‘node-cron’);
const printData = () => { console.log(“Hello dear”) };
// schedule takes two arguments, cron time and the task to call when we reach that time. I used a random time ad task here so you can change it.
cron.schedule(’10 20 23 9 1′
printData())
You can use the example below to incorporate it in your app:
const allSubscriptions = {}
const registerTasks = (subscription) => { const endpoint = subscription.endpoint;
// Calculate time according to your location, the time below is an example.
const morningTask = cron.schedule(‘30 23 * * *‘, () => { sendNotification(subscription, JSON.stringify({ timeOfDay: ‘morning‘ })); });
const afternoonTask = cron.schedule(‘30 6 * * *‘, () => { sendNotification(subscription, JSON.stringify({ timeOfDay: ‘afternoon‘ })); });
const nightTask = cron.schedule(‘15 14 * * *‘, () => { sendNotification(subscription, JSON.stringify({ timeOfDay: ‘evening‘ })); }); allSubscriptions[endpoint] = [morningTask, afternoonTask, nightTask]; };