I was trying to run an API call at a scheduled time. I researched through sites and found this package called node-schedule from npmjs. This is working as expected by calling the code at required time. The issue I am having is :
Suppose I have a list of times eg: ["10:00","11:00","13:00"]
Once I start the server, it will get executed at required times. But what if I want to change the time list dynamically?
Exactly what I am trying to do:
- Call API and get times from Database
- Setup cron-schedule for each of these times.
- Dynamically adding new time to database
What I want: Dynamically add this newly added time to the cron-schedule
index.js
const express = require('express');
const schedule = require('node-schedule');
const app = express();
const port = 5000;
var date = new Date(2019, 5, 04, 14, 05, 20);// API call here
var j = schedule.scheduleJob(date, function(){
console.log('The world is going to end today.');
});
app.get('/test', (req, res) => {
var date = new Date(2019, 5, 04, 14, 11, 0); // Will call API here
var q = schedule.scheduleJob(date, function(){
console.log('Hurray!!');
});
res.send('hello there');
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
The code written above is what I have and its pretty messed up. What I am conveying there is that, while running the index.js
file API is called and the cron-schedule
gets executed. Now if there is some new values added to DB I want to rerun this.
Rerunning index.js
is another option I have, but I don't think its the right thing to do. The next option I have in mind is to call another endpoint which is mentioned as /test
above, which would eventually run the cron again.
Please let me know some suggestions or some sort of solution to this so I can rectify my mistakes.