node-schedule是一个用node实现的任务调度系统,比起不太好配置的crontab,用来管理同用javascript写的定时脚本实在是再合适不过。

以下是为之前的虾米签到脚本写的task runner:

schedule = require 'node-schedule'
process = require 'child_process'
fs = require 'fs'

log = null

rule = new schedule.RecurrenceRule()

if process.env is 'development'
  rule.second = 1 # 每隔一分钟,测试用
else
  rule.hour = 1 # 凌晨1点签到

# 写入log文件中
writeLog = (text)->
  log = fs.createWriteStream('log.txt', {'flags': 'a', encoding: 'utf-8'})
  log.end(text)

run = ()->
  child = process.spawn 'casperjs', ['xiami_casper.coffee']

  child.stdout.on('data', (data)->
    text = new Date() + data.toString()
    writeLog(text)
    console.log text
  )

  child.stdout.on('end', ()->
    writeLog("Run job on #{new Date().toString()}")
  )

  child.on 'error', ()->
    console.log arguments

job = schedule.scheduleJob(rule, ()->
  run()
)

上传到vps上,用forever来启动runner长时间运行:

forever start -c coffee schedule_runner.coffee