Skip to content

Instantly share code, notes, and snippets.

@methodin
Created November 30, 2011 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save methodin/1407864 to your computer and use it in GitHub Desktop.
Save methodin/1407864 to your computer and use it in GitHub Desktop.
Run function for a Node cron job
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');
)
)
)
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
)
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