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'});
});
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