How to write cronjobs in seperate file nodejs - node.js

I want to write a cron job on node.js which runs every minute. The tutorials that I viewed online all showed the cron job being written in the "App.js" or "server.js" file which is the main file on nodejs.
I want to seperate this into another file for better readability but I cannot find any solution or example online. please help.
I want to write this in a separate file just like we write our routes.
const cron = require("node-cron");
cron.schedule("* * * * *", function() {
console.log("running a task every minute");
});

You can create and export javascript modules elsewhere in your express/node.js app like this:
app.js
const express = require('express');
const app = express();
const port = 5000;
require('./tasks/tasks')();
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`)
});
tasks.js
const cron = require('node-cron');
module.exports = () => {
cron.schedule('* * * * *', () => {
console.log('running a task every minute');
});
}
Terminal:
[nodemon] starting `node start app.js`
App listening at http://localhost:5000
running a task every minute
File Structure:
/tasks
tasks.js
app.js

yes. you can write your cron-job in separte file. when starting the server, you can invoke your cron job, like in your app.js or server.js. you just export your cron job file & impore here
import cronJob from "../filename.js"
server.listen(3000, () => {
cronJob.start();
});

node-cron emulates, rather than uses, the UNIX / Linux / FreeBSD cron subsystem driven by crontab file entries. node-cron projects the illusion that functions in a running nodejs instance can be scheduled as if they were executable programs.
If you want to schedule a different nodejs program as a cron job, don't use node-cron, use cron. Put an entry in the OS's crontab mentioning the nodejs program.

Related

node-cron only working with an active session

I have a simple node-cron schedule that calls a function:
cron.schedule('00 00 00 * * *', () => {
console.log('update movies', new Date().toISOString());
updateMovies();
});
When I log in to my server using PuTTy or use the droplet console in Digital Ocean and then run the updateMovies.mjs file node server/updateMovies.mjs and wait for the time that the cron-job should run, everything works as expected.
But when I close PuTTy or the droplet console in Digital Ocean, then nothing happens when the cron-job should run. So the server seems to lose the cron-job when I close the session.
Short answer
You need to run the app in the background
nohup node server/updateMovies.mjs >/dev/null 2>&1
Long answer
Run your app directly in the shell is just for demos or academic purposes. On an enterprise environment you should a live process like a server which runs independently of the shell user.
Foreground and background processes
Processes that require a user to start them or to interact with them are called foreground processes
Processes that are run independently of a user are referred to as background processes.
How run background process (Linux)
No body uses windows for an modern deployments, so in Linux the usual strategy is to use nohup
server.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/plain');
res.send('Hell , its about time!!');
});
app.listen(process.env.PORT || 8080);
nohup node server.js >/dev/null 2>&1
If you login to the server using some shell client, and run only node server.js it will start but if you close the shell window, the process will ends.
How run background process with nodejs and PM2
pm2 server.js
More details here:
https://pm2.keymetrics.io/docs/usage/quick-start/
Best way : Docker
You need to dockerize your app and it will run everywhere with this command:
docker run -d my_app_nodejs ....

Run a task every 30 seconds in Heroku

I want a Nodejs application running on Heroku to run a task every 30 seconds. I use Heroku scheduler for another task but that's because it runs once a day and Scheduler seems fine for that, but to run at this interval it is not suitable.
So I have installed node-cron and setup a job that would run every 30 seconds, daily, between 11am and 6pm (I am basically calling an api and then updating a database), locally I can run this fine with node cron.js
cron.js
const cron = require('node-cron');
const task = require('./scripts/task');
cron.schedule('*/30 * 11-18 * * *', () => {
console.log('Running Function');
task.runFunction();
});
I'm not 100% sure how to run this on Heroku, from their docs they specify this kind of setup (configured in Procfile):
web: node web.js
worker: node worker.js
clock: node clock.js
Current Procfile
web: node server.js
Is it a case of changing my cron.js to clock.js ? and then having something in a worker.js file? (though unsure as to what).
You should probably change the clock.js to cron.js, or, as you say, rename cron.js to clock.js.
web: node web.js
worker: node worker.js
clock: node cron.js
Also, I'm not sure your cron.js is set up correctly. From the documentation on node-cron, it looks like you might need something that looks like this:
const CronJob = require('../lib/cron.js').CronJob;
console.log('Before job instantiation');`
const job = new CronJob('*/30 * 11-18 * * *', () => {
console.log('Running Function');
task.runFunction();
});
console.log('After job instantiation');
job.start();
You don't need this line worker: node worker.js if in your cron.js you don't tell him to do somethings with this worker. (I don't know what runFunctions() do). And you don't even need to add the first line if your application is just cron jobs.
So you can just have this Profile :
clock: cron.js
You can change clockto cron if you want. It doesn't mean: docs.

How can I run my node js script automatically using scheduler on server

I have created a nodejs file using express enviornment and running the file on server using nodemon. Currently I have to give commands to the interface to run the particular file on nodemon but what I currently need is to schedule the task to run that file on server automatically at multiple occasion in a single day.
my file excute like this on terminal::
nodemon example_api.js
output terminal:
root#*********:/var/www/example project# nodemon example_api.js
[nodemon] ##.##.#####
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node api.js`
Listening on port 8080
Note: I am currently running node js on Mobaxterm terminal currently using windows but my file will be run on a server with linux interface
1. If you want to run your node process continuously and want to run only particular task:
Use node-schedule or node-cron packages to run your code block at desired time or interval.
i.node-schedule
var schedule = require('node-schedule');
var j = schedule.scheduleJob('*/30 * * * * ', function(){
console.log('The answer to life, the universe, and everything!');
});
ii.node-cron
var cron = require('node-cron');
cron.schedule('*/30 * * * *', function(){
console.log('The answer to life, the universe, and everything!');
});
2. If you want to run only single node script:
You can use Linux crontab to execute your script at desired time
crontab -e
and add following entry
*/30 * * * * /usr/local/bin/node /home/ridham/example/script.js
This will execute /home/ridham/example/script.js every 30 minutes. and always give full qualified path here.
You have to give crontime in any of the following. you can learn about crontime here
For a simple implementation - you can just use setInterval like so:
setInterval(() => {
// do something every 5 seconds
}, 5000);
But it you want something like a cron, then, you might wanna go with node-cron or node-schedule.
You can also use providers like AWS CloudWatch. AWS CloudWatch allows you to run AWS Lambda functions on a cron.

node-cron task works even when server is restarted with node-cron task commented in my nodejs server

I m using package for task sechdule in my nodejs/parseserver open source
https://www.npmjs.com/package/node-cron
but even i comment the job and restarted servert ...job seems running.....can some one guide me here??
var counter=0;
Parse.Cloud.define("test", function(request, response) {
response.success(counter+1);
});
//var cron = require('node-cron');
//var task=cron.schedule('*/1 * * * *', function(){
/* Parse.Cloud.run('test',{}, {
success: function(results) {
console.log('test');
response.success(results);
},
error: function(error) {
response.error("Some error.");
}
}); */
//console.log('job creared loop');
//});
It sounds like the file where the cronjob is, is not loading with the changes. But some information is missing from your question I think.
Which server are you referring to & what server:
1. Are you just running the node fafa.js program again?
2. Are you working with Forever or PM2? If PM2 you need to
sudo pm2 restart [name of file]
Are you completely restarting the whole server??? (AWS etc)
Perhaps a simple
console.log("see if cron job runs")
within the code will show you what is going on. Obviously if the console.log does not appear the old code is still running.
I think if the above is not the case we would need more information.

Cronjob not running when restart app or server

I have Cronjob use node_module: node-cron
var hello = function( ) {
console.log('Hello world')
}
var job=new CronJob({cronTime:'00 52 13 * * *',
// that's important (100% made up example):
onTick: function() {
hello({
done: true,
lastRun: new Date()
});
},
start:false,timeZone:"America/Los_Angeles"});
job.start();
when I restart server .Cronjob not running.
node scripts that uses node-cron still have to be started for the cronjob to run. Adding things to node-cron, does not add it to cron on your machine, even though the naming can be confusing. node-cron simply allows your script to schedule jobs inside your script, while your script is running.
For this to work, either convert to scheduling the script on your machine, using the built in scheduler, or start your node script on machine startup. (This is different depending on your operating system).

Resources