mongodb-cron icon indicating copy to clipboard operation
mongodb-cron copied to clipboard

Cron running twice for the same job.

Open pabloherre opened this issue 11 months ago • 1 comments

I have a single job entry in the database, when the server time reach the sleepUnitl time, the job is being executed twice inside the onDocument method.

Here are my settings:

MongoDB Schema

const schema = new Schema(
    {
      name: { type: String, required: true },
      sleepUntil: { type: Date, default: new Date(), required: true },
      interval: { type: String, required: true },
      data: { type: Schema.Types.Mixed }
    },
    {
      timestamps: true
    }
  );

MondoDB Entry

{
    "_id": ObjectId("65d37bbf7933cf20f1064ee3"),
    "name": "JOB_TO_RUN",
    "interval": "0 0 6 * * *",
    "sleepUntil": ISODate("2024-03-19T09:00:00.000Z"),
    "data": {},
    "updatedAt": ISODate("2024-03-01T15:15:14.647Z")
}

Cron job execution code

const { MongoCron } = require('mongodb-cron');

module.exports = async app => {
  const mongooseClient = app.get('mongooseClient');
  const collection = await mongooseClient.connections[0].collections['cron-jobs'];

  const cron = new MongoCron({
    collection,
    onStart: () => console.info('\t✓ Cron jobs.'),
    onDocument: doc => console.count(), // You will get a 2 console logs here!
    onError: async err => console.error(err),
    nextDelay: 1000,
    reprocessDelay: 1000,
    idleDelay: 1000
  });

  cron.start();
};

pabloherre avatar Mar 21 '24 17:03 pabloherre