在NodeJS中安排一个异步函数

时间:2019-10-21 11:17:05

标签: javascript node.js typescript async-await

我想安排一个异步(异步/等待ruturn类型)的函数每两分钟运行一次。

我尝试使用通用的setInterval节点模块,例如node-schedule,cron,node-cron,async-poll,但是无法实现对异步函数调用的轮询。

这是我在代码中尝试过的:

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

2 个答案:

答案 0 :(得分:2)

尝试这样的事情

// 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”才能使其正常工作。

日程表库需要一个函数来执行,但是在上面的示例中,它们得到了已解决的Promise。

答案 1 :(得分:0)

就我而言,我使用的是 async/await 函数,例如:

myService.ts :

    @Cron(CronExpression.EVERY_10_SECONDS)
  async myExample() {
    const todaysDate: dayjs.Dayjs = dayjs();
    Logger.log(`Cron started at ${todaysDate}`);
    const users = await this.myRepo.getUsers();
   // code here
  }

myRepo.ts :

    getUsers() {
    return this.myModel.find({});
  }

但它不起作用所以改变了 myService.ts 并尝试了 then :

    @Cron(CronExpression.EVERY_10_SECONDS)
  async myExample() {
    const todaysDate: dayjs.Dayjs = dayjs();
    Logger.log(`Cron started at ${todaysDate}`);
    this.myRepo.getUsers().then(users => {
      // code here
    });
  }
相关问题