How could I make node-cron run only once?

810 views Asked by At

I want to console log "hi" in 10 minutes but only once. How could I achieve this with node-cron?

Tried to use some others but they failed to do the job.

1

There are 1 answers

0
esqew On

node-cron supports passing a Date object to fire an event at a specific date and time. From node-cron's README.md:

Additionally, this library goes beyond the basic cron syntax and allows you to supply a Date object. This will be used as the trigger for your callback.

API

[...]

  • CronJob
    • constructor(cronTime, onTick, onComplete, start, timezone, context, runOnInit, utcOffset, unrefTimeout)
      • cronTime - [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS Date object.

[...]

In short, create a Date() object that represents the time 10 minutes from execution:

const cron = require('node-cron');

const datetime = new Date();
const adjustedDatetime = datetime.setMinutes(datetime.setMinutes() + 10); 
const eventDatetimeObject = new Date(adjustedDatetime);

cron.schedule(eventDatetimeObject, () => console.log("hi"));