Avoiding more than one cronjob in parallel in node.js - node.js

I would like to do some cronjob using the Node.js package "cron" every 10 minutes.
This cronjob takes between 5 to 15 minutes, and I don't want that in a case that one instance is still running - another will be joining it in parallel. Instead, it will skip the additional running and wait until the next period.
Is it possible to implement it using this package?
Here is the code of the implementation using the cron package :
const CronJob = require("cron").CronJob;
const job = new CronJob(
'0 */10 * * * *',
()=>SomeCronJob(),
null,
true,
'America/Los_Angeles',
);
I thought of implementing it using a combination of simple setInterval() and clearInterval() instead of the package, not sure how though.
I'd appreciate any help!

I would use a flag to check if the job is running. Example:
let isJobRunning = false;
function SomeCronJob() {
if (isJobRunning) {
// Skip
return;
}
isJobRunning = true;
// run stuff
// Once is finished
isJobRunning = false;
}

Related

How to run a function after a given time in node.JS?

I am building a hosting server with node.JS and mongoDB.
The server will be used for people to save their files remotely. But I do not want to keep unattended files on the server because it will be a waste of memory on the server.
So there are two things I wish to do :
Delete Files if not attended for more than 10 days
Leave the Files otherwise
Is there a way this can be done easily?
You can use cron job for this type of scheduled task. NodeJS has a module named cron to perform a scheduled task.
Approach:
Every day at midnight you will check for unattended files. If you find any unattended file then you can delete it.
Example code:
const CronJob = require('cron').CronJob;
new CronJob('0 0 * * *', async () => {
// Find files
// Delete files
}, null, true, 'America/Vancouver', null, false);
You can schedule a cron and it will check for your condition and do the desired action.
https://www.npmjs.com/package/cron
example:
var CronJob = require('cron').CronJob;
var job = new CronJob('* * * * * *', function() {
console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');
job.start();

Stopping and starting execution of cron-job-manager (node-cron) upon condition

So, I found an old question about this (here: How to stop a node cron job) but it doesn't work for me (and I can't realize the reason why).
I'm using cron-job-manager (since I plan to use more than one scheduled job at the same time) but as far as I know it should be built on node-cron (but I'm a newbie, so...)
So, I'm asking again: how do I deal with starting and stopping a cron job under certain conditions?
I'm actually doing this for a discord bot: basically, the user input a command for starting and one for stopping.
First try was something like:
job = cron('keyTask','* * * * * *', ()=>{
//Do the actual job
},
{
start: false,
timeZone:"Europe/London",
});
switch args[1]
case go:
job.start();
break;
case stop:
job.stop();
break;
This start the job successfully when the user gives the 'go' command, but when it gives the 'stop' command, the scheduled job just won't stop.
Second try is:
var x = args [1];
new cron('keyTask' , '* * * * * *', job(doTheThing(x)) ,
{
start: false,
timeZone:"Europe/London",
});
Where job() is a function defined beforehand that contains the actual job and DoTheThing() is something that gives true or false depending on what the user is saying in input.
This executes the scheduled job once and then stops.
Somehow I suspect that the issue here is related to the fact that I'm defining function externally, while in most examples I saw the function is always written within the cron().
So, I'm out of ideas: thanks in advance for any help!

can cron schedule a variable change in one of your scripts (node.js)

is it possible to get cron to go into one of your scripts on the server and change a variable at a certain time?
cron simply fires a program/script at a given time. You would need an intermediate script/program to change the variable. But you could schedule a script to run that changes your variable.
You can install cron npm module to do it:
$ yarn add cron
And then in your code:
const CronJob = require('cron').CronJob;
let i = 0;
new CronJob('* * * * * *', function() {
console.log('You will see this message every second');
i++;
console.log(`Value of i = ${i}`);
}, null, true, 'America/Los_Angeles');

How to use Generic cron jobs in node application?

I have node application in which I want to run tasks on daily basis. So I want to use node-cron to schedule tasks but not like this:
var cron = require('node-cron');
cron.schedule('* * * * *', function(){
console.log('running a task every minute');
});
I need some generic solution so that at one place I have just empty body for cron job that takes different functions from a different location. That means in total we have two files, one which has just cron job function handler and other have a list of cron jobs. From where we want to run these jobs we just need require and some basic calling.
Can anyone suggest me this solution?
I got my solution. Using node-cron-job module I have achieved what I wanted. Let me explain in detail:-
First i created new file which contains jobs, lets name it jobs.js :-
// jobs.js
exports.first_job = {
on:"* * * * * " //runs every minute
},
job: function () {
console.log("first_job");
},
spawn: true
}
exports.second_job = {
on: "*/2 * * * * *", //runs every 2 second
job: function () {
console.log("second_job");
},
spawn: false // If false, the job will not run in a separate process.
}
Here, we define two jobs name first_job and second_job. We can define as many required.
Finally, we need to call these jobs from any location by these simple steps:-
// main.js
var cronjob = require('node-cron-job');
cronjob.setJobsPath(__dirname + '/jobs.js'); // Absolute path to the jobs module.
cronjob.startJob('first_job');
cronjob.startJob('second_job');
We can call all jobs in a single call like this:-
cronjob.startAllJobs();

looking for a node.js scheduler that wont start if the job is still running

I'm looking for a schedular/ cron for nodejs.
But I need an important feature- if the jobs did not finish (when the time for it to start again arrived), I want it to not start/ delay the schedule.
For example, I need to run a job every 5 minutes. The job started at 8:00, but finished only at 8:06. so I want the job of 8:05 to either wait until 8:06, or not to start at all, and wait for the next cycle at 8:10.
Is there a package that does that? If not, what is the best way to implement this?
You can use the cron package. It allows you to start/stop the cronjob manually. Which means you can call these functions when your cronjob is finished.
const CronJob = require('cron').CronJob;
let job;
// The function you are running
const someFunction = () => {
job.stop();
doSomething(() => {
// When you are done
job.start();
})
};
// Create new cronjob
job = new CronJob({
cronTime: '00 00 1 * * *',
onTick: someFunction,
start: false,
timeZone: 'America/Los_Angeles'
});
// Auto start your cronjob
job.start();
You can implement it by yourself:
// The job has to have a method to inform about completion
function myJob(input, callback) {
setTimeout(callback, 10 * 60 * 1000); // It will complete in 10 minutes
}
// Scheduler
let jobIsRunning = false;
function scheduler() {
// Do nothing if job is still running
if (jobIsRunning) {
return;
}
// Mark the job as running
jobIsRunning = true;
myJob('some input', () => {
// Mark the job as completed
jobIsRunning = false;
});
}
setInterval(scheduler, 5 * 60 * 1000); // Run scheduler every 5 minutes

Resources