英文:
node-schedule: Cannot read property of undefined when restarting job
问题
我正在使用node-schedule在我的Node服务器上安排任务,我是这样做的:
jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url)));
这个方法运行良好。在设置的日期上,end_auction
函数会正确执行。每次我启动服务器时,我从数据库中检索当前的拍卖,并为它们创建任务,以便它们在服务器崩溃时仍然存在。我是这样做的:
var now = new Date();
for(var i = 0; i < plates.length; i++){
if(now >= plates[i].expires_on){
end_auction(plates[i].url);
}else{
jobs.push(schedule.scheduleJob(new Date(plates[i].expires_on), () => end_auction(plates[i].url)));
}
}
然而,我的问题是,使用上述方法创建的每个任务都无法正确执行。在设置的时间,而不是调用end_auction
函数,我会得到以下错误:
Cannot read properties of undefined (reading 'url')
,它指向plates[i].url
我可以使用console.log()
很好地读取plates
的属性,所以我不确定问题出在哪里。有人可以帮助我吗?谢谢。
英文:
I am using node-schedule to schedule jobs on my node server, I do it like this:
jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url)));
This works fine. On the set date, the end_auction
function executes correctly. Every time I start my server, I retrieve the current auctions from the database and create jobs for them so that they persist if the server was to crash. I do it like so:
var now = new Date();
for(var i = 0; i < plates.length; i++){
if(now >= plates[i].expires_on){
end_auction(plates[i].url);
}else{
jobs.push(schedule.scheduleJob(new Date(plates[i].expires_on), () => end_auction(plates[i].url)));
}
}
However, my problem is that every job which is created with the above method fails to execute correctly. At the set time, instead of calling the end_auction
function, I will instead get this error:
Cannot read properties of undefined (reading 'url')
which points to plates[i].url
I can read the properties of plates
just fine using console.log()
so I am not sure what the issue is. Can anyone assist me with this? Thanks.
答案1
得分: 1
这可能是因为在安排任务后更改了您的 "plates" 数组值。
要在将来的作业中使用当前数据,您可以按照 node-schedule 文档 中的说明,在回调函数中使用绑定。
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const x = 'Tada!';
const job = schedule.scheduleJob(date, function(y){
console.log(y);
}.bind(null,x));
x = 'Changing Data';
这将在计划的作业运行时记录 'Tada!',而不是立即更改为 'Changing Data' 的 x。
英文:
This may be because your "plates" array value has been changed after scheduling the job.
To use current data in the future job you can use binding in the callback function as per node-schedule documentation.
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const x = 'Tada!';
const job = schedule.scheduleJob(date, function(y){
console.log(y);
}.bind(null,x));
x = 'Changing Data';
This will log 'Tada!' when the scheduled Job runs, rather than 'Changing Data', which x changes to immediately after scheduling.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论