NodeJS Cron Job with Kue
2012/10/26 4 Comments
At Cozy we needed to write some jobs of this kind for our Mails app. For that we used Kue a simple task manager for NodeJS that requires Redis to run. The documentation is great but there was no sample for writing a cron task. That’s why I share this little snippet that runs a 2 seconds long job every 3 seconds, in case you need something similar.
NB : The delay between each job is set in minutes.
kue = require 'kue' Job = kue.Job jobs = kue.createQueue() # Set up server if you want to see your task progression with a beautiful UI kue.app.listen 3003 # Your cron timing delay = 3000 # Function used to launch a job. repeatJob = -> job = jobs.create "test complete", title: "my job" info: "job is working" job.on 'promotion', () -> console.log job.data.title + " #" + job.id + " promoted" job.delay(delay) job.save() # The job to run, a fake task that is 2 seconds long. cronTask = (job, done) -> global.currentJob = job.id console.log job.data.title + " #" + job.id + " job started" setTimeout -> console.log "my job is done" repeatJob() done() , 2000 # Register job jobs.process "test complete", myFunc = cronTask # Check for new job every 3s, change this value to set your cron timing. jobs.promote(delay) # Run the cron job for the first time. repeatJob()