pm2 how to avoid schedule cron lock in nestjs - cron

I use pm2 to run the service. I have a total of 2 clusters.
And I created a schedule job in nestjs and executed the schedule,
but both clusters ran schedule and the database was locked.
how can i avoid this?
below is my ecosystem.js
module.exports = {
apps: [
{
name: 'my_app',
script: 'dist/main.js',
instances: 0,
exec_mode: 'cluster',
listen_timeout: 10000,
kill_timeout: 1000,
},
],
};

i can use process.env.pm_id
pm2 list
check my pm_id list
#Cron('* * * * ... ')
myCron(){
if(process.env.pm_id === '0') {
...
}
}

Related

Is it possible to use ignore_watch parameter by extension or wildcard in PM2?

I'm using pm2 for my node application. But whenever I travel between folders, or if I click to "stage changes" in VSCode, PM2 restarts the application.
I believe osX creating files like .DS_Store etc. and that triggers pm2 watch.
So I can add a wildcard to ignore that kind of file for every folder.
This is how my process.json looks like;
{
"apps": [{
"name": "server",
"script":"index.js",
"max_memory_restart": "1024M",
"node_args":"--max_old_space_size=2048",
"watch":true,
"ignore_watch":["ext/server/reports", "node_modules", ".git", ".vscode"],
"args":"dev",
"env_local": {
"NODE_ENV": "local"
},
...
}]
}
Yes, it is possible. Put a file named as ecosystem.config.js on the root of project.
module.exports = {
apps : [{
name: 'project_name',
script: 'index.js',
instances: 1,
autorestart: true,
restart_delay: 5000,
watch: true,
max_memory_restart: '512M',
ignore_watch: ['log-*.txt'],
error_file: 'log-error.txt',
out_file: 'log-output.txt'
}]
};
Here the parameter as ignore-watch will help you. e.g. In my case, I am ignoring the files as log-output.txt, log-error.txt.

How to prevent grunt-nodemon from restarting all apps

I'm running node on Windows 10. I have three node apps and I want to be able to start them all up with one handy grunt command. Furthermore, I want node to automatically restart if I modify any of the apps.
I'm using a combination of grunt-nodemon and grunt-concurrent for this. The node processes all start up fine.
The problem is that if I modify the code related to any of them they all restart, which takes a long time. How can I make it so that nodemon only restarts the app whose code I actually modified?
var loadGruntTasks = require('load-grunt-tasks')
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concurrent: {
runAll: {
tasks: ['nodemon:app1', 'nodemon:app2', 'nodemon:app3'],
options: {
logConcurrentOutput: true
}
}
},
nodemon: {
app1: {
script: './app1/app.js'
},
app2: {
script: './app2/app.js'
},
app3: {
script: './app3/app.js'
}
}
})
loadGruntTasks(grunt)
grunt.registerTask('default', ['concurrent:runAll'])
}
Update
If I use grunt-watch instead of grunt-nodemon, only the app whose code I modified will restart. The problem is that grunt-watch only knows to run node app.js which gives an error because the app is already running. Is there a way to make grunt-watch kill the node process and restart it?
I think the answer could be fairly simple. Nodemon has an ignore option. For each of your three applications nodemon grunt configurations you can configurate them to ignore the directories of the other applications. That way they only kick off their restart when their own files are changed and not those of other projects. Let me know how that goes. :) Specifics about setting up the ignore section of config can be found in both nodemons documentation and grunt-nodemons documentation.
Patrick Motard's answer made me think about what directory nodemon was running in and how it was observing the files for changes. It appears that since I started grunt inside the parent directory of all the node apps that each nodemon process was looking for changes in all of those directories. So I set the working directory of the nodemon processes to the corresponding directory for each app using the options.cwd setting. That seemed to fix it. Here is the working solution:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concurrent: {
runAll: {
tasks: ['nodemon:app1', 'nodemon:app2', 'nodemon:app3'],
options: {
logConcurrentOutput: true
}
}
},
nodemon: {
app1: {
script: 'app.js',
options: {
cwd: './app1'
}
},
app2: {
script: 'app.js',
options: {
cwd: './app2'
}
},
app3: {
script: 'app.js',
options: {
cwd: './app3'
}
}
}
})
loadGruntTasks(grunt)
grunt.registerTask('default', ['concurrent:runAll'])
}

How to watch and reload an ExpressJS app with pm2

I'm developing an ExpressJS app.
I use pm2 to load it:
myapp$ pm2 start bin/www
This works fine, except that adding the --watch flag doesn't seem to work; every time I change the JS source I need to explicitly restart it for my changes to take effect:
myapp$ pm2 restart www
What am I doing wrong? I've tried the --watch flag with a non-ExpressJS app and it worked as expected.
See this solution in Stack Overflow
The problem is relative to the path where pm2 is watching, and if it is relative to the execution file or the actual root path of the project.
2021 Feb.
Things have changed a bit now. Gave a full example below from my project. Below works:
1 . Create config file. File: ecosystem.config.js
module.exports = {
apps: [
{
name: 'api',
script: './bin/www', // --------------- our node start script here like index.js
// ------------------------------------ watch options - begin
watch: ['../'],
watch_delay: 1000,
ignore_watch: ['node_modules'],
watch_options: {
followSymlinks: false,
},
// ------------------------------------ watch options - end
env: {
NODE_ENV: 'development',
PORT: 3001,
DEBUG: 'api:*',
MONGODB_URI:
'mongodb://localhost:27017/collection1?readPreference=primary&ssl=false',
},
env_production: {
NODE_ENV: 'production',
},
},
],
deploy: {
production: {
// user: "SSH_USERNAME",
// host: "SSH_HOSTMACHINE",
},
},
};
2 . Run server (dev/ prod)
pm2 start ecosystem.config.js
pm2 start ecosystem.config.js --env production
3 . More information :
https://pm2.keymetrics.io/docs/usage/watch-and-restart/
You need to specify the app location to the --watch option
myapp$ pm2 start bin/www --watch /your/location/to/app
I never managed to make default watch settings work in Ubuntu, however using polling via advanced watch options worked:
"watch": true,
"ignore_watch" : ["node_modules"],
"watch_options": {
"usePolling": true,
"interval": 1000
}
More info:
https://github.com/buunguyen/PM2/blob/master/ADVANCED_README.md#watch--restart
https://github.com/paulmillr/chokidar#api

How to create api documents with grunt-ngdocs

I'm trying to create API documents through grunt-ngdocs.
The partials are created but the index.html doesn't have the correct links to it.
I have in my gruntfile.js:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
uglify: {
options: {
// the banner is inserted at the top of the output
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'web/js/app.min.js': ['web/js/app.js']
}
}
},
ngdocs: {
options: {
dest: 'docs',
scripts: ['web/js/app.js'],
title: 'My Documentation'
},
api: {
src: ['web/**/*.js'],
title: 'API Documentation'
}
},
clean:['docs','testResult']
});
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-ngdocs');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('default', ['clean','uglify', 'ngdocs', 'karma']);
};
and my js file like this
/**
* #ngdoc overview
* #ngdoc directive
* #name myApp.maincontroller:controller
* #description
*
* # myApp
* The factoryName is my favorite service in the world.
*
*/
var myApp = angular.module('myApp',[]);
myApp.controller("MainController", function($scope) {
$scope.model = {
myValue: "Run you fools!"
};
});
/**
* #ngdoc function
* #name mySuperFunction
* #returns {int} The int representing a Firebase resource
*/
function mySuperFunction() {
var i = 5;
var j = 5;
i += j;
return i;
}
but when I run
grunt
in the command line, the result is this
C:\Users\Lino Simões\Documents\bitbucket\test>grunt -d --force
Running "clean:0" (clean) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-contrib-clean\tasks\clean.js
Cleaning docs...OK
Running "clean:1" (clean) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-contrib-clean\tasks\clean.js
Cleaning testResult...OK
Running "uglify:dist" (uglify) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-contrib-uglify\tasks\uglify.js
File web/js/app.min.js created: 796 B → 210 B
Running "ngdocs:api" (ngdocs) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-ngdocs\tasks\grunt-ngdocs.js
Generating Documentation...
DONE. Generated 2 pages in 256ms.
Running "karma:unit" (karma) task
[D] Task source: C:\Users\Lino Simões\Documents\bitbucket\test\node_modules\grun
t-karma\tasks\grunt-karma.js
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Windows 7)]: Connected on socket dFX-dKGVINA6PBjB5Gu9 wit
h id 91061839
PhantomJS 1.9.7 (Windows 7): Executed 8 of 8 SUCCESS (0.008 secs / 0.004 secs)
Done, without errors.
so, this generates 2 files, but when I go to the index.html under docs I have this:
but in my docs/partials/api/ I have the partials created by the ngdocs.
my project tree is like this:
Did you have angular.js and angular-animate.js in your web/js/app.js? Check it. And add to "options" html5Mode: false
for ng1.6 works for me:
ngdocs: {
all: ['app/**/*.js']
}
you will see the old version of angular 1.2.* in
cat docs/js/angular.min.js | grep v1
AngularJS v1.2.16
but it does not affect your source files.
also, dont forget run server
for generated folder docs:
e.g using python
pushd ./dist; python -m SimpleHTTPServer 9000; popd #v 2.*
pushd ./dist; python -m http.server 9000; popd #v 3.*
unfortunately, adding angular.js and angular-animate.js to scripts option doesn't work for me

Grunt concurrent task outputting nothing

I want my Grunt based setup to run both "test" (i.e. the unit tests) and "server" (i.e. the web server) at the same time, so that I can just do grunt testAndServer to run both (and update both when any file is changed) in the same terminal.
Code (much of it is based on the yo angular scaffold):
// in initConfig:
concurrent: {
testAndWebServer: [
'karma',
'watch'
]
},
and later
grunt.registerTask('testAndServer', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'concurrent:server',
'autoprefixer',
'compass',
'connect:livereload',
'open',
'concurrent:testAndWebServer'
]);
});
This actually works, but I don't get any output in the terminal (PowerShell) window. I would like the karma task to show the results of the tests. How can I acheive that?
I am running Node.js v0.10.20 on Windows 7, on a quadcore machine.
I just realized that I missed the logConcurrentOutput option.
This makes it work:
testAndWebServer: {
tasks: ['watch', 'karma'],
options: { logConcurrentOutput: true }
},

Resources