How to use Generic cron jobs in node application? - cron

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();

Related

Node: Storing function names in a variable and then calling them

I am writing a node application that uses node-cron to schedule certain function to run at specific times. Currently the code for this is embedded in the main application. I want to move the configuration of scheduled tasks out to a config file, so want need to store the function names in a variable to achieve this, as the schedule tasks call out a number of functions in different modules etc.
For information the syntax to schedule a cron task is this:
cron.schedule('* * * * *', () => {functiontocall()});
The code block below shows how I am currently storing the tasks in an object and trying to schedule them with node-cron.
mycronobj = [
{scheduletime : "* * * * *", schedulefunction : 'testfunction1'},
{scheduletime : "*/5 * * * *", schedulefunction : 'testfunction2'},
{scheduletime : "*/10 * * * *", schedulefunction : 'testfunction3'},
]
for (item in mycronobj) {
cron.schedule(mycronobj[item].scheduletime, () => {mycronobj[item].schedulefunction()});
}
However this doesn't work, the scheduled functions don't run. I have tried storing the functions names as a string (as shown) or direct as
{scheduletime : "* * * * *", schedulefunction : testfunction1()}
When trying to add the scheduled function I have tried this with the following syntaxes:
mycronobj[item].schedulefunction()
mycronobj[item]schedulefunction
mycronobj[item].schedulefunction
None of which have worked for me. I have tried looking for an answer to this and I tried using eval(), but this also didn't work correctly, the outcome was that a task with first schedule ("* * * * *") was scheduled with the last function 'testfunction3' was applied, also I dont really want to use eval as I have read its not great practice and can be avoided if you know what your doing (clearly I don't).
Other options I have come across is to use Window which doesn't exist in Node or This, which I cannot get to work either.
Thanks in advance.
The reason your code isn't working is that mycronobj[item]schedulefunction is a string so is not invokable. You need to turn this string into a reference to the function with the same name.
The simplest solution to this is using eval, e.g:
for (item of mycronobj) {
cron.schedule(item.scheduletime, () =>
eval(`${item.schedulefunction}()`);
}
However this is a really bad idea, and allows for arbitrary code execution which is generally considered a very bad thing (tm).
Node gives you a slightly safer alternative to this using the vm module, which can create a limited sandbox in which your code can execute:
const vm = require("vm");
let context = vm.createContext({ foo });
for (item of mycronobj) {
cron.schedule(item.scheduletime, () =>
vm.runInContext(`${item.schedulefunction}()`, context);
}
This is only marginally better though since it can still allow arbitrary code execution, so by far the safest option is just to explicitly list exactly which functions are allowed to be called:
const commands = {
testfunction1: () => console.log("I am 1"),
testfunction2: () => console.log("I am 2"),
testfunction3 // Reference existing function
}
function testfunction3() { console.log("I am 3"); }
for (item of mycronobj) {
let func = commands[item.schedulefunction];
if (!func) { throw new Error(`Unknown command: "${item.schedulefunction}"`); }
cron.schedule(item.scheduletime, func);
}
This also has the benefit of determining during setup whether functions are valid rather than only when the cron job runs.

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();

Avoiding more than one cronjob in parallel in 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;
}

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

I want to create a cron job with nodejs, but How can I check that the previous job is finished or not?

I want to create a cron job with nodejs. But How can I check the previous is finished or not? I just want one job is running at the same time.
There is a great library for cron jobs in Node.JS: cron
The "nature" of cron jobs is that they are be executed periodically. If you want a job to start only if the previous job has finished, you can use a flag (set it to true at the start of the job, set it to false at the end of the job - then new jobs can check if the flag is true).
BUT, maybe you should use a job queue - once a job has finished, the next job will start executing. That depends on your scenario, so please provide more information.
A popular library that has queues: collections.
You could combine cron and async's queues, for example:
var CronJob = require('cron').CronJob;
var async = require('async');
var NUMBER_CONCURRENT_JOBS = 1;
var q = async.queue(function(task, callback) {
task(callback);
}, NUMBER_CONCURRENT_JOBS);
var job = function(callback) {
setTimeout(function() {
console.log('JOB EXECUTED');
callback();
}, 5000);
}
new CronJob('* * * * * *', function() {
console.log('JOB REQUIRED');
q.push(job);
}, null, true, 'America/Los_Angeles');

Resources