Home > Blockchain >  schedule route or controller
schedule route or controller

Time:04-17

i have a controller

exports.updateDaily = async (req, res) => {
  try {
    const updateDaily = await transaction.decrement(
      {
        remainActive: 1,
      },
      {
        where: {
          remainActive: { [Op.gte]: 1 },
        },
      }
    );
    console.log(updateDaily);
    res.status(200).send({
      status: "Success",
    });
  } catch (error) {
    console.log(error);
    res.status(400).send({
      status: "Failed",
    });
  }
};

and route like this

router.patch('/updateDaily', updateDaily)

Using cron-node

let job = new cron.schedule('2 * * * *', () => {
    router.patch('/updateDaily', updateDaily);
});
job.start()

Using setIntverval

const scheduller = () => {
     return router.patch('/updateDaily', updateDaily);
}
setInterval(scheduller,600000)

how can i make one of them run every 10 minutes? i already try it with node-cron or setInterval but there is nothing happen

CodePudding user response:

You got the concept wrongly. Having a scheduled job means running something periodically which has to be a function that does something. You don't need a router defined in it. Your code does only one thing - schedules a router to be available for the user once the scheduled time happens and redefines it every 10 minutes.

What you need is to create a separate function for the operation and call it on a scheduled time and having a router at this point is extra unless you want to run it when the user sends a request as well.

const myDailyTask = async () => {
  await transaction.decrement(
    {
      remainActive: 1,
    },
    {
      where: {
        remainActive: { [Op.gte]: 1 },
      },
    }
  );
};

const id = setInterval(myDailyTask, 600_000);

It should work for the cron job the same way

const job = new cron.schedule('2 * * * *', () => {
    myDailyTask();
});
job.start();
  • Related