JP.
JP.

Reputation: 1075

cron job not running for node js

I want to run a script that will add new records into the mongodb.

* * * * * echo ‘Run this command every minute’ >> file.log
* * * * * node /home/ubuntu/mongodb_tutorial-movies/getMovies.js
* * * * * node /home/ubuntu/mongodb_tutorial-movies/start.sh

updated code:

* * * * * echo ‘Run this command every minute’ >> file.log
* * * * * node /home/ubuntu/mongodb_tutorial-movies/start.sh
* * * * * usr/local/bin/node /home/ubuntu/mongodb_tutorial-movies/getMovies.js

updated code 2:

which node
/usr/local/bin/node


PATH=/usr/sbin:/usr/bin:/sbin:/bin:usr/local/bin/node
* * * * * echo ‘Run this command every minute’ >> file.log
* * * * * node /home/ubuntu/mongodb_tutorial-movies/start.sh
* * * * * usr/local/bin/node /home/ubuntu/mongodb_tutorial-movies/getMovies.js
* * * * * node /home/ubuntu/mongodb_tutorial-movies/getMovies.js

here "/home/ubuntu/mongodb_tutorial-movies/getMovies.js" is the location of the js file.

Cron job runs for first script i.e it logs echo text into the file.log but due to some reason it doesnt run the second script.

I also tried 3rd script but no effect. Contents of .start.sh

node getMovies.js

code for getMovies.js

var colors = require('colors'); 
var mongoose = require('mongoose');

var db = mongoose.connection;

db.on('error', console.error);
db.once('open', function() {

});

mongoose.connect('mongodb://localhost/movie-db');

var movieSchema = new mongoose.Schema({
  title: String
, rating: String
, releaseYear: Number
, hasCreditCookie: Boolean
});

var Movie = mongoose.model('Movie', movieSchema);

var thor = new Movie({
  title: 'Thor'
, rating: 'PG-14'
, releaseYear: '2011'  
, hasCreditCookie: true
});

thor.save(function(err, thor) {
  if (err) return console.error(err);
  console.dir(thor);
});

console.log(' every 6 secodns '.green);

Upvotes: 0

Views: 5210

Answers (1)

geert3
geert3

Reputation: 7321

For security reasons, Cron's $PATH contains only the bare minimum like /bin and /usr/bin. So likely node isn't on cron's $PATH. Solution may be to replace node in your crontab file with the full path to the executable, e.g. /opt/node/bin/node - you can find out the exact location on your system by typing which node in the shell.

Also, to run a shell script from the crontab, you don't need the node executable, so remove that from the third line. The resulting crontab would then look like this (assuming /opt/node/bin/node is the full path, see above)

* * * * * echo ‘Run this command every minute’ >> file.log
* * * * * /opt/node/bin/node /home/ubuntu/mongodb_tutorial-movies/getMovies.js
* * * * * /home/ubuntu/mongodb_tutorial-movies/start.sh

Upvotes: 1

Related Questions