node-cron only working with an active session - node.js

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

Related

hosting a discord bot on cPanel

I have a problem that when I want to turn on my discord bot on my server that uses cPanel, I can't get it to work from the node.js control panel without putting the shell command node index.js into the package.json file and using the run script function of the panel. the problem with this is that the only way to stop the bot is to use the eval command on discord, since I don't have proper terminal access.
In addition to what #Verdigris answered above, you can use Glitch too, just make sure to use Runtime Bot so you can keep your Discord bot up 24/7.
Important: code to add on your main node.js file:
const http = require('http');
const express = require('express');
const app = express();
app.get("/", (request, response) => {
console.log(Date.now() + "Ping Received");
response.sendStatus(200);
});
app.listen(process.env.PORT);
setInterval(() => {
http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 280000);
And as always, cheers.
On cPanel you will never have full terminal access, so what I suggest you do is just keep the NPM start script, then create a command for the bot that issues the process.exit() function. This function essentially stops the entire NodeJS Process. If you are looking for an alternative that provides full terminal access I recommend buying a cheap VPS from a decent provider such as OVH.
If your cPanel account has a in-browser terminal, you can enter the virtual environment by pasting the command that appears at the top of the Node.js control panel into there. It is something like:
source ~/nodevenv/<name_of_node_application>/10/bin/activate && cd ~/<path_to_node_application>
You will then have access to node and npm, and can then start your discord bot like you normally would like:
node <name_of_node_application> &
and kill it by running kill -TERM with node's pid, from ps -ax.
However, you can't reliably use the Node.js panel to stop a daemon script, as described here:
cpanel node.js Can't acquire lock for app: app

How to start nodejs application automatically on openwrt - Arduino Yun -

I am trying to have a nodejs application start automatically on system boot. Basically all I need is to run the command node /dir/app.
I am using openwrt on an Arduino Yun. And have tried a couple things.
On the openwrt website it said I can do this. https://wiki.openwrt.org/inbox/procd-init-scripts :
#!/bin/sh /etc/rc.common
USE_PROCD=1
start_service() {
procd_open_instance
procd_set_param command node ///www/www-blink.js
procd_close_instance
}
I have also tried changing the dir to /www/www-blink.js not ///
However i'm not sure what i'm doing wrong as nothing comes up when I try run it with /etc/init.d/node-app start I am obviously writing the code wrong but i'm not sure what it should exactly look like.
The other thing I have tried is the node modules forever and forever-service.
I downloaded them on my computer using npm install -g forever and forever-service aswell. I transfered them to usr/lib/node_modules on my arduino yun. However when I try to use and forever(-service) commands it says
-ash: forever: not found
I have tried a couple other things, however nothing has worked. Any help would be greatly appreciated.
-- I also need to be able to start my express script with npm start not node app but I guess the first thing is getting it to work at all.
you can put the starting command (node /dir/app &)in the /etc/rc.local script. This will start your nodejs application automatically on system boot.
OpenWRT procd has a "respawn" parameter, which will restart a service that exits or crashes.
# respawn automatically if something died, be careful if you have an
# alternative process supervisor if process dies sooner than respawn_threshold,
# it is considered crashed and after 5 retries the service is stopped
procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
So, you cold just add:
procd_set_param respawn 60 5 5
or something like that to your OpenWRT procd initscript. This 60 5 5 means it will wait 5s between respawns (middle parameter), and if it respanws more than 5 times (last parameter) in 60s (first parameter), it will disable the service ("restart loop" detected).
Refer to this page for more information:
https://openwrt.org/docs/guide-developer/procd-init-scripts
You need to execute your node application like a Linux Service.
Upstart is perfect for this task
Upstart is an event-based replacement for the /sbin/init daemon which handles starting of tasks and services during boot, stopping them during shutdown and supervising them while the system is running.
If you have an app like this (for example):
// app.js
var express = require('express')
var app = express()
var port = process.env.PORT
app.get('/', function(req, res) {
res.send('Hello world!')
})
app.listen(port)
With a package.json like this:
{
"name": "my-awesome-app",
"version": "1.0.0",
"dependencies": {
"express": "^4.13.3"
},
"scripts": {
"start": "node app.js"
}
}
We create a upstart configuration file called myAwesomeApp.conf with the following code:
start on runlevel [2345]
stop on runlevel [!2345]
respawn
respawn limit 10 5
setuid ubuntu
chdir /opt/myAwesomeApp.conf
env PORT=3000
exec npm start
To finish, put your application (app.js and package.json) in the /opt/myAwesomeApp.conf and copy the configuration file myAwesomeApp.conf in /etc/init/
This is all, now you just need to run service myAwesomeApp start to run your node application as a service
I've never used procd before, but it likely needs the full path to node (e.g., /usr/bin/node). You'd need to make the line something like procd_set_param command /usr/bin/node /www/www-blink.js, assuming the file you want to run is /www/www-blink.js. You can locate node by running which node or type -a node.

Code Deploy ApplicationStart gets stuck on pending using node

Hi I'm new to using Code Deploy. I am trying to launch a node application. I have setup.sh, start.sh and app.js in my root directory.
This is my appspec.yml file
version: 0.0
os: linux
files:
- source: /
destination: /
hooks:
Install:
- location: setup.sh
timeout: 3600
ApplicationStart:
- location: start.sh
timeout: 3600
setup.sh
yum -y install nodejs npm --enablerepo=epel
npm install
start.sh
node /app.js
app.js (just a basic dummy server)
var express = require("express");
var app = express();
app.get("/",function(req,res) {
res.send("Hello world")
})
var server = app.listen(8080,function() {
console.log("Listening at " + server.address().address + ": " + server.address().port);
});
The Install step successfully completes, but Code Deploy gets stuck on pending when it does the ApplicationStart step.
I'm pretty sure it's because the app.js program runs continously, so how is CodeDeploy supposed to know that it's working and move on?
The CodeDeploy agent is waiting for the script it launched to return an exit code and to close stdout and stderr. To start a process in the background and detach it from the host agent so it can run as a daemon, try:
node /app.js > /dev/null 2> /dev/null < /dev/null &
Note: you'll want to modify your program to write to a log file instead of the console, since daemons usually don't have a console to write to (as it is in this version).
See the official docs here: http://docs.aws.amazon.com/codedeploy/latest/userguide/troubleshooting.html#troubleshooting-long-running-processes
The command node /app.js does not run in background but in foreground, therefor the start.sh script is never finished.
See this thread for more info about running node in background Node.js as a background service

How to Restart nodeJS screen app without reboot PC

I trying to restart nodejs app which is running in background screen app.
But here i can't do these without reboot my PC. I used forever module but it's start when i reboot my PC but I actually want one button on web-page and when I click on that automatically start node app without restart my PC.
Any One have iDEA about these please let me guide what to Do ?
NOTE : without reboot my system working
You can execute commands from nodejs like this :
nodejs
var child_process = require('child_process');
child_process.exec('forever restart', function callback(error, stdout, stderr) {
// console.log(stdout);
});

Run process at startup on Express JS

Is there a way to run a process at startup on Express.js?
I want to run a continuous process that will execute every 30 minutes, but it should run always and start running when Express applications is started.
You can set up a cron task in nodejs. You need to set crontab on the server to call a path in node every 30 minutes and then have the path execute the task required.
app.get('/cron', function(req, res){
runPeriodicTask();
return;
});

Resources