My goal is to be able to run different functions in each of the multiple node schedule jobs, which will run at specific times of the day, and will call a specific function depending on the time of the day.
I have the following code, for a minimum example I have made it simple.
var f1 = function () {
return fetch('url1.php', {
method: 'post',
headers: {
'Content-Type': 'application/json'
}
})
}
var f2 = function () {
return fetch('url2.php', {
method: 'post',
headers: {
'Content-Type': 'application/json'
}
})
}
var tasks = [f1, f2];
const promesas = async(tasks) => {
return await Promise.all(tasks.map(function (e, j) {
rules[j] = new schedule.RecurrenceRule();
rules[j].dayOfWeek = [new schedule.Range(1, 5)];
rules[j].hour = hours[j];
rules[j].minute = mins[j];
return schedule.scheduleJob(rules[j], async function () {
try {
await tasks[j]()
} catch (error) {
console.log(error);
}
});
})).then(response => {
return Promise.resolve(response);
});
}
promesas(tasks);
I can run these functions just fine outside the jobs, or all within a single job. But not in the setup that I want which I describe at the beggining.
The first iteration works fine, the second just fails. The difference between each job is of one minute for testing purposes.
I am not sure what you're doing here, especially with your odd use of Promises. (Why await
the Promise.all()
? Why return Promise.resolve()
of the already resolved response
? Why await
each individual task rather than just let it execute (or fail) asynchronously in what amounts to a cronjob script with no output?)
However, if this is working for you for the first iteration, that's fine.
Can I assume you're using node-schedule? If so, just note that you're actually using times of day 00:00, 01:01, etc. rather than "one minute between each for testing purposes" as you claim.
Here's how I would do what you seem to be trying to do:
const tasks = [f1, f2];
let i = 0;
for (let task of tasks) {
let rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [new schedule.Range(1, 5)];
rule.minute = (new Date().getMinutes() + (++i)) % 60; // adjust to suit your needs
schedule.scheduleJob(rule, task);
}
I have confirmed this works, e.g. issues one task per minute starting from the minute after the script is started. No await
, then
, or Promise.all
is necessary for the simple example you have given, but may be required depending on what you plan to do with the results of each job function.