0

I have a node js controller

const calculateInitialStartTime = (
 startDate,
 frequency,
 timeOfDay,
 dayOfWeek,
 dayOfMonth
) => {
 let initialStart = new Date(startDate);
 if (timeOfDay) {
 const [hour, minute] = timeOfDay.split(":");
 initialStart.setHours(hour);
 initialStart.setMinutes(minute);
 initialStart.setSeconds(0);
 } else {
 initialStart.setHours(7);
 initialStart.setMinutes(0);
 initialStart.setSeconds(0);
 }
 switch (frequency) {
 case "weekly":
 const day = initialStart.getDay();
 const targetDay = dayOfWeek || 0;
 const diff = (targetDay - day + 7) % 7;
 initialStart.setDate(initialStart.getDate() + diff);
 break;
 case "monthly":
 const monthDay = dayOfMonth || 1;
 if (initialStart.getDate() > monthDay) {
 initialStart.setMonth(initialStart.getMonth() + 1);
 }
 initialStart.setDate(monthDay);
 break;
 }
 return initialStart;
};
const getCronExpression = (frequency, timeOfDay, dayOfWeek, dayOfMonth) => {
 let cronTime = "0 7"; // Default to 7:00 AM
 if (timeOfDay) {
 const [hour, minute] = timeOfDay.split(":");
 cronTime = `${minute} ${hour}`;
 }
 switch (frequency) {
 case "hourly":
 return "0 * * * *"; // Every hour at minute 0
 case "daily":
 return `${cronTime} * * *`; // Daily at specified time
 case "weekly":
 return `${cronTime} * * ${dayOfWeek || 0}`; // Weekly on specified day and time
 case "monthly":
 return `${cronTime} ${dayOfMonth || 1} * *`; // Monthly on specified day and time
 default:
 throw new BadRequestError("Invalid frequency");
 }
};
agenda.define(`thrift job wallet`, async (job, done) => {
 try {
 const { thriftId, userId, email, name } = job.attrs.data;
 const thriftSave = await ThriftSave.findOne({ _id: thriftId });
 const wallet = await Wallet.findOne({ user: userId });
 if (thriftSave.status === "completed") {
 await job.remove();
 logger.info(`Job removed for completed thrift: ${thriftId}`);
 return done();
 }
 if (!wallet) {
 throw new BadRequestError("No Wallet found");
 }
 if (+wallet.amount < +thriftSave.per) {
 await sendFailedWalletDebitEmail({
 email,
 title: `Thrift - ${thriftSave.title}`,
 amount: thriftSave.per,
 });
 await Transactions.create({
 user: userId,
 username: name,
 amount: thriftSave.per,
 title: `Thrift - ${thriftSave.title}`,
 type: "debit",
 status: "success",
 });
 throw new BadRequestError("Insufficient funds");
 }
 await Wallet.updateOne(
 { user: userId },
 { $inc: { amount: -thriftSave.per } }
 );
 await ThriftSave.updateOne(
 { _id: thriftId },
 { $inc: { amount: thriftSave.per } }
 );
 await Transactions.create({
 user: userId,
 username: name,
 amount: thriftSave.per,
 title: `Thrift - ${thriftSave.title}`,
 type: "debit",
 status: "success",
 });
 done();
 } catch (error) {
 logger.error(`Error processing thrift job: ${error.message}`);
 done(error);
 }
});
agenda.define(`recurringThrift job wallet`, async (job, done) => {
 const { thriftId, userId, email, name, cronExpression } = job.attrs.data;
 await agenda.every(cronExpression, `thrift job wallet`, {
 thriftId,
 userId,
 email,
 name,
 });
 job.remove();
});
const createThriftSave = async (req, res) => {
 const { title, frequency, per, startDate, timeOfDay, dayOfWeek, dayOfMonth } =
 req.body;
 const { id, email, name } = req.user;
 const startDateObj = new Date(startDate);
 const initialStartTime = calculateInitialStartTime(
 startDate,
 frequency,
 timeOfDay,
 dayOfWeek,
 dayOfMonth
 );
 const cronExpression = getCronExpression(
 frequency,
 timeOfDay,
 dayOfWeek,
 dayOfMonth
 );
 const interest = 0;
 const thrift = await ThriftSave.create({
 title,
 amount: 0,
 frequency,
 startDate: startDateObj,
 per,
 interest,
 user: id,
 });
 await agenda.schedule(
 initialStartTime,
 `recurringThrift job wallet`,
 {
 thriftId: thrift._id,
 userId: id,
 email,
 name,
 cronExpression,
 }
 );
 await sendThriftEmail({ email, title, per, frequency });
 res.status(StatusCodes.OK).json({ thrift });
};

This is supposed to schedule a job at a future time and then that job triggers a recurring job according to the set interval..

My issue is that when it schedules one job, the next time a job is scheduled, it replaces the previous one and that one is lost, i think because these jobs are of the same name..Is there a way i can make multiple jobs be created with the different job.attrb.data but the same name?

asked Jun 10, 2024 at 22:29
6
  • There are two separate logics here. First, build a cron expression. Second, set and run a job. Please clarify if the expression is not built correctly or you have a job scheduling problem. Hint: Can you schedule a job using a static cron expression? Commented Jun 11, 2024 at 11:40
  • Are you suggesting i separate the cron expression outside the createThriftSave function? My problem is that the function doesn't run when it is scheduled. Commented Jun 11, 2024 at 12:16
  • The source of your issue is not clear to me. The problem can be an incorrect cron expression, or misconfiguration of the job. By adding a testing job with a static and known CRON, the source of the problem can be detected more easily. Say. if the job with a static CRON gets run, the issue is related to building the CRON exp. otherwise, the problem is somehow related to scheduling and the library. Commented Jun 11, 2024 at 12:35
  • I have updated my question..My issue is that a new job replaces the previous scheduled job..I just need to make multiple instead of just one that is replaced over and over Commented Jun 11, 2024 at 18:19
  • Jobs are replaced with the same name so assign a unique name to every job. Commented Jun 12, 2024 at 5:43

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.