0

i am trying to make api which can generate attendance daily at 9:50Am it's only operate once but not daily


const server = app.listen(process.env.PORT, () => {
  console.log(`Server is working on http://localhost:${process.env.PORT}`);
});
cron.schedule(
  "24 10 * * *",
  async () => {
    let date = new Date();
    date = date.toISOString().split("T")[0].split("-").reverse().join("/");
    console.log("morning");

    const Users = await Employee.find({ shift: "morning" });
    console.log(Users);
    Users.forEach(async (user) => {
      const attendance = await Attendance.create({
        user: user._id,
        status: "absent",
        date,
      });
      console.log(attendance);
    });
  },
  {
    scheduled: true,
    timezone: "Asia/Karachi",
  }
);

can anyone explain why it is not working on daily basis my server is live on heroku and how to fix this?

  • if the Attendance.create() is waiting for a date format, you sent a string and it couldnt be recognized by your database. You should use a date GMT 0 in your db and convert when you do request. – pirs Nov 07 '22 at 05:58
  • yes yes brother but i am saving my date in string format in my mongodb database my scheduler is working fine but its only operate once not daily – hamza irfan Nov 07 '22 at 06:11
  • MongoDB asks for generic date format like new Date() or Date.toISOString(), it is mandatory if I think right. But you save the date as string, and I guess mongo dont recognized it. Then the conversion is in request. I mean you convert you date GMT 0 when you save it. – pirs Nov 07 '22 at 06:14
  • Meantime the issue could be in you CRON Try to put '* * * * 23' instead – pirs Nov 07 '22 at 06:18
  • 1
    If you're running on Heroku, are you sure your app keeps running? If it doesn't, it won't run the scheduled code either. – AKX Nov 07 '22 at 07:31
  • yes on heroku its working fine everything in my project is working but i just have an issue with node-cron – hamza irfan Nov 07 '22 at 08:20

1 Answers1

0

forEach is not meant to be used with await, try with a normal for ... of loop.
Also, if you want to schedule it at 9:50Am you should specify 50 9 * * *.

cron.schedule(
  '50 9 * * *',
  async () => {
    let date = new Date();
    date = date.toISOString().split('T')[0].split('-').reverse().join('/');
    console.log('morning');

    const Users = await Employee.find({ shift: 'morning' });

    for (const user of Users) {
      const attendance = await Attendance.create({
        user: user._id,
        status: 'absent',
        date,
      });
      console.log(attendance);
    }
  },
  {
    scheduled: true,
    timezone: 'Asia/Karachi',
  }
);
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29