Created
November 30, 2011 03:31
-
-
Save methodin/1407864 to your computer and use it in GitHub Desktop.
Run function for a Node cron job
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require './schema.js' | |
| mongoose = require "mongoose" | |
| mongodb = require "mongodb" | |
| sys = require 'sys' | |
| lock = require './lock.js' | |
| run = require './run.js' | |
| # Sample cron | |
| # * * * * * /usr/local/bin/node /var/some/dir/cron.js > /var/log/cronjs.log | |
| run.attempt('every 1 minute', () -> | |
| lock.check('one', (conflict) -> | |
| return false if conflict | |
| # Pull all the links that expire today | |
| # This is done by selecting links via <date logged> - timeframe | |
| # Then sending out emails | |
| db = mongoose.connect(mongurl) | |
| Link = mongoose.model('links', LinkSchema) | |
| date = new Date() | |
| # Iterate through items | |
| Link.find( | |
| date_expire: | |
| $gte: new Date() | |
| ).sort('date','descending').execFind((err,docs)-> | |
| console.log(err) if err | |
| // Do something with docs | |
| lock.destroy() | |
| process.kill(process.pid, 'SIGTERM'); | |
| ) | |
| ) | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fs = require 'fs' | |
| path = require 'path' | |
| lockPath = "/var/www/some/dir/" | |
| lockFile = '' | |
| process.on('SIGTERM', () -> | |
| process.exit(1) | |
| ) | |
| exports.check = (filename, contents..., callback) -> | |
| lockFile = "#{lockPath}/#{filename}.lock" | |
| path.exists lockFile, (exists) -> | |
| fs.writeFileSync(lockFile, contents.join('')) unless exists | |
| console.log "Lock file #{filename} already exists. Exiting..." if exists | |
| callback exists | |
| exports.destroy = () -> | |
| path.exists(lockFile, (exists) -> | |
| fs.unlinkSync(lockFile) if exists | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| exports.attempt = (time, callback) -> | |
| d = new Date | |
| hours = d.getHours() | |
| minutes = d.getMinutes() | |
| m = time.match(/every ([0-9]+) hours?/) | |
| if(minutes == 0 && m && hours % m[1] == 0) then return(callback()) | |
| m = time.match(/every ([0-9]+) minutes?/) | |
| if(m && minutes % m[1] == 0) then return(callback()) | |
| false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment