I have an array of objects. For each object I need to set a schedule.
'node-schedule'
to reset the schedule I need it in a variable.
function setSchedule(ticket) {
const date = new Date(2012, 11, 21, 5, 30, 0);
const job = schedule.scheduleJob(date, function () {
console.log('The world is going to end today.');
});
}
how can I bind the object to his own schedule function? I mean, later I need to know which schedule I need to reset.
I would to it something like, but I think there is a better way?
const job[ticket.id] = schedule.scheduleJob(date, function () {
console.log('The world is going to end today.');
});
The job variable will be available in the closure of the scheduled callback function, if referenced.
Consider, for instance, the following code, which is very similar to your own situation:
const handle =
setInterval(function() {
console.log("callback");
clearInterval(handle);
}, 100)
The callback fired once, then was cancelled by means of the handle variable that exists in an outer scope.
Ok, now i solve it this way
function setSchedule(ticket) {
if (ticket.blocked) {
const date = new Date(ticket.blockedDate);
scheduleJob[ticket._id] = schedule.scheduleJob(
{
date: date.getDate(),
month: date.getMonth(),
year: date.getFullYear(),
},
() => {
console.log('Run' + ticket._id);
scheduleJob[ticket._id].cancel();
Ticket.updateOne(
{ _id: ticket._id },
{ blocked: false, blockedDate: null }
)
.then(() => {})
.catch((error) => {
console.log(error);
});
}
);
}
if (!ticket.blocked && scheduleJob[ticket._id]) {
scheduleJob[ticket._id].cancel();
}
}
What do you think? Is these a common way to use the id for array?