0

I just started using cron, but I can not find a way to schedule a one time job. What I have is working for me, but I want to know if there is a better way to achieve it.

The code below creates a job and prints in console that it was created. I set the timer every 1 second, but just below I do a sleep with 1.5s to stop the job.

const express = require('express');
const cron = require('node-cron');
const router = express.Router();

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// Schedule a job on GET
router.get('/', (req, res, next) => {
  const job = cron.schedule(`*/1 * * * * *`, () => {
    console.log('job created');
  });
  sleep(1500).then(() => {
    job.stop();
  })
  
  return res.status(200).json({ message: 'scheduled'});
});
Duncanista
  • 83
  • 1
  • 8

2 Answers2

2

You can build cron expression something like below. "0 0 7 8 9 ? 2020" (seconds min hour dayOfMonth Month DayofWeek Year) , this will run only once. You need to build this expression based on the first day/time you want the job to run. If you need to run immediately, you can build cron expression based on the current time + some seconds buffer

snp
  • 36
  • 1
  • Thank you so much, it actually worked, but I also npm confused me so I used another package which is still the same(? – Duncanista Sep 07 '20 at 23:07
0

As snp suggested, I had to create a cron expression with the nearest date plus some seconds. But also, I realized the package node-cron is totally different to cron, even though their redirect to the same place.

I solved it like this:

const express = require('express');
const cron = require('cron'); // <- change of package
const router = express.Router();
const cronJob = cron.CronJob; // <- get the cron job from the package

const getDateAsCronExpression = () => { ... }

// Schedule a job on GET
router.get('/', (req, res, next) => {
  const cronExpression = getDateAsCronExpression();
  var job = new cronJob(cronExpression, () => {
    console.log('job executed!');
  }, null, true, 'your_time_zone_here');
  
  return res.status(200).json({ message: 'scheduled'});
});

Duncanista
  • 83
  • 1
  • 8