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

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.

Related

How to make the node js code always run even if the system is shutdown

i have created the cron job using node js ,which have to run in the interval of every hour even if the system is shut down. It has to run automatically with out manual invoke of the code .Please help to solve this
i have tried with pm2 but not working as expected.
First you should install npm package for crone-job
npm i node-cron
And then you can follow this code for your automatic job
const schedule = require("node-cron");
schedule.scheduleJob("00 02 * * *",
function () {
console.log("The answer to life, the universe, and everything!");
expected_Function_Name();
});
You will get your function output in every day 2pm.

How to write cronjobs in seperate file nodejs

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.

How do I restart a Node.js server internally in the script on global error?

I've been browsing around but to no success. I've found some npm packages like nodemon and forever but documentation doesn't explain how to call a restart inside the script properly.
I've found this code snippet on another question but I'm not using Express or other frameworks since the script is using a pulling service not a response one.
This is code I've made so far using internal Node.js dependencies but no luck.
'use strict'
process.on('uncaughtException', (error) => {
console.error('Global uncaughtException error caught')
console.error(error.message)
console.log('Killing server with restart...')
process.exit(0)
})
process.on('exit', () => {
console.log('on exit detected')
const exec = require('child_process').exec
var command = 'node app.js'
exec(command, (error, stdout, stderr) => {
console.log(`error: ${error.message}`)
console.log(`stdout: ${stdout}`)
console.log(`stderr: ${stderr}`)
})
})
setTimeout(() => {
errorTriggerTimeBomb() // Dummy error for testing triggering uncaughtException
}, 3000)
Just to note I'm running the server on Termux, a Linux terminal app for android. I know it's better to run from desktop but I'm always at a WiFi or mobile data area and that I don't like leaving my PC on overnight.
A typical restart using something like nodemon or forever would be triggered by calling process.exit() in your script.
This would exit the current script and then the monitoring agent would see that it exited and would restart it for you. It's the same principal as if it crashed on its own, but if you're trying to orchestrate it shutting down, you just exit the process and then the monitoring agent will restart it.
I have a home automation server that is being monitored using forever. If it crashes forever will automatically restart it. I also have it set so that at 4am every morning, it will call process.exit() and then forever will automatically restart it. I do this to prevent any memory leak accumulation over a long period of time and 30 seconds of down time in the middle of the night for my application is no big deal.

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).

Sending emails when Node.js app crashes with forever or forever-monitor

I'm using forever to run my Node.js server and I very like it's start/stop/restart command line commands. Recently I decided that I need system that will email me about all server crashes. Unfortunately forever doesn't support such kind of functionality out of the box.
So I decided to take forever-monitor (the tool like forever but with programmatic approach) and nodemailer. Here is a script I wrote:
var forever = require('forever-monitor');
var nodemailer = require('nodemailer');
var sendmailTransport = require('nodemailer-sendmail-transport');
var transporter = nodemailer.createTransport(sendmailTransport({
path: '/usr/sbin/sendmail'
}));
var error = '';
function sendMail(subject, text) {
var message = {
// sender info
from: '"Server name" <no-reply#example.com>',
// Comma separated list of recipients
to: '"My name" <myemail#example.com>',
// Subject of the message
subject: subject,
// plaintext body
text: text
};
transporter.sendMail(message, function (err) {
if (err) {
console.log('Error during trial email with server error report');
console.log(err);
}
});
}
var child = new (forever.Monitor)('app.js', {
outFile: './logs/stdout.log',
errFile: './logs/stderr.log'
});
child.on('stderr', function (data) {
error += data;
});
// Check for errors every second
setInterval(function () {
if (error) {
sendMail('Your server crashed', error);
error = '';
}
}, 1000);
child.start();
I called this file start.js. All it does is: spawns new process (app.js, which runs my Express web-server) with forever-monitor, I listen for stderr event of this child process and collect all errors into variable, then I check this variable every second and if it doesn't empty I send an email and clear variable. This code works fine.
Now to start my server I need execute something like nohup node start.js &. The bad thing that there is no easy way to stop or restart my server. Previously I did it with forever stopall and forever restartall which is very convenient.
My next thought was try to combine forever and forever-monitor so I tried to start server like this forever start start.js. Server started just like I supposed. But restarting didn't work anymore. Executing forever stopall and then forever start start.js didn't work too. Server started to complain that port is already busy. I assume it happens because forever stops start.js process, but the child app.js process spawned by forever-monitor still was occupying the port.
So my question is: how to run Node.js server, receive emails about it's crashes, automatically restart it when it crashed and have possibility to easily start/stop/restart it like with forever command line utility? Solution can use forever, forever-monitor or both of them, or actually any library you think may work for this kind of problem.
I think you should fork forever's git repository and add emails notifications in source code. This way you can still use forever CLI without additional scripts.
If you're not familiar with concept check out: https://help.github.com/articles/fork-a-repo/
Seems like such a feature have been already requested but without much reply.
With working solution you can either add your (forked) repo to your package.json or contribute to forever project by requesting pull. Maybe thanks to you forever will have email notifications.

Resources