Skip to content

Instantly share code, notes, and snippets.

@JonathanTurnock
Last active July 5, 2023 01:28
Show Gist options
  • Save JonathanTurnock/6d8a32f0f8f2565aa99bd14ff6718829 to your computer and use it in GitHub Desktop.
Save JonathanTurnock/6d8a32f0f8f2565aa99bd14ff6718829 to your computer and use it in GitHub Desktop.
Job Scheduler
const express = require('express');
const schedule = require('node-schedule');
const { addMinutes, isValid, parseISO } = require('date-fns');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json()); // for parsing application/json
const port = 3000;
let jobCount = 0;
let nextJobDate = new Date();
let currentJob = null;
function doSomeWork() {
console.log('Doing some work for job ' + (++jobCount));
}
// Function to schedule a job
function scheduleJob(date) {
// Cancel the current job if it exists
if (currentJob) {
currentJob.cancel();
}
nextJobDate = date;
currentJob = schedule.scheduleJob(date, function(){
console.log(`Executing job ${jobCount + 1} at ${new Date()}`);
// Do the work
doSomeWork();
// Schedule the next job 10 minutes after this one completes
let nextDate = addMinutes(new Date(), 10);
scheduleJob(nextDate);
});
}
// Schedule the first job 10 minutes from now
let startDate = addMinutes(new Date(), 10);
scheduleJob(startDate);
app.get('/health', (req, res) => {
res.json({ nextJobDate });
});
app.post('/schedule', (req, res) => {
const date = parseISO(req.body.date);
if (!isValid(date)) {
return res.status(400).send({ error: 'Invalid date' });
}
scheduleJob(date);
res.send({ message: `Job scheduled for ${date}` });
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment