Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule an async function in NodeJS

I want to schedule a function which is asynchronous (async/await ruturn type) to run for every two minutes.

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(" */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
like image 888
cslrnr Avatar asked Oct 21 '19 11:10

cslrnr


2 Answers

Try something like this

// 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());

I don't know about your servicesManager, you might have to use "version 2" from above to get it to work.

The schedule libraries need a function to execute, but instead they get a resolved Promise in the examples above.

like image 105
kraf Avatar answered Sep 28 '22 08:09

kraf


Scheduled asynchronous calls won't work using node-cron at least up to v3.0.0, but we can use node-schedule for this as follows.

JS

schedule.scheduleJob("*/1 * * * *", async () => await this.lifeService.addLife(userId, 1));

TS

import nodeSchedule = require("node-schedule");

const job: nodeSchedule.Job = nodeSchedule.scheduleJob('*/10 * * * * *', async () => {
    const life = await this.lifeService.getLives(userId);
    console.log(`user's life`, life);
});

like image 22
Nathan Getachew Avatar answered Sep 28 '22 06:09

Nathan Getachew