-1

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
    "*Tried to use some others but they failed to do the job.*" In the future, you should include your attempt(s) in the body of your question in accordance with the guidelines on creating a [mre], as well as [ask]. – esqew May 08 '23 at 18:27
  • Please provide enough code so others can better understand or reproduce the problem. – Community May 08 '23 at 21:18

1 Answers1

0

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:

var cron = require('node-cron');
const date = new Date().setMinutes(new Date().getMinutes() + 10); // h/t https://stackoverflow.com/questions/4517672/how-to-add-20-minutes-to-a-current-date
cron.schedule(date, () => console.log("hi"));
esqew
  • 42,425
  • 27
  • 92
  • 132