在NodeJS中安排异步功能 [英] Schedule an async function in NodeJS
问题描述
我想安排一个异步(异步/等待ruturn类型)的函数每两分钟运行一次.
I want to schedule a function which is asynchronous (async/await ruturn type) to run for every two minutes.
我尝试使用通用的setInterval
节点模块,例如 node-schedule,cron,node-cron,async-poll ,但是无法实现对异步函数调用的轮询.
I tried with generic setInterval
, node modules like node-schedule , cron, node-cron, async-poll but unable to achieve polling for a async function call.
这是我在代码中尝试过的:
This is what I tried in code:
cron.schedule("*/2 * * * *", await this.servicesManager.startPoll() => {
console.log('running on every two minutes');
}); // this is not working breaks after first run
const job = schedule.scheduleJob(" star/1 * * * *", async function() {
try {
return await this.ServicesManager.startPoll(); // this function startPoll is undefined when using this
} catch (e) {
console.log(e);
}
console.log('Run on every minute');
});
const event = schedule.scheduleJob("*/2 * * * *", this.ServicesManager.startPoll()); //using node-schedule , breaks after first time
cron.schedule("*/2 * * * *", await this.ServicesManager.startPoll()); // using cron same result as using node-schedule
return await this.ServicesManager.startPoll(); // without polling works
推荐答案
尝试类似的方法
// version 1
cron.schedule("*/2 * * * *", this.servicesManager.startPoll);
// version 2 => if servicesManager needs its `this` reference
cron.schedule("*/2 * * * *", async () => this.servicesManager.startPoll());
//version 3 ==> using node-schedule
schedule.scheduleJob("*/1 * * * *", async () => this.ServicesManager.startPoll());
我不知道您的servicesManager
,您可能需要使用版本2"从上面开始工作.
I don't know about your servicesManager
, you might have to use "version 2" from above to get it to work.
计划库需要一个函数来执行,但是在上面的示例中,它们得到了已解决的Promise.
The schedule libraries need a function to execute, but instead they get a resolved Promise in the examples above.
这篇关于在NodeJS中安排异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!