Created
March 16, 2016 18:58
-
-
Save mikermcneil/6d4a7129b08ea177c63a to your computer and use it in GitHub Desktop.
example of a background 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
/** | |
* Module dependencies | |
*/ | |
var SailsApp = require('sails').Sails; | |
// e.g. `jobs/clean-up-orphaned-images` | |
var sails = new SailsApp(); | |
sails.load({ hooks: {grunt: false} }, function afterwards(err) { | |
if (err) { | |
console.error('Failed to load sails:',err); | |
return; | |
} | |
// Do your stuff-- your models and services and such are now accessible. | |
// this is just a self-calling function to ensure that sails.lower() gets called either way | |
(function _doYourStuff (done){ | |
// e.g. destroy orphaned "File" records from more than 12 hours ago which were never associated with a user | |
var twelveHoursAgo = new Date( (new Date()).getTime() - (12*60*60*1000) ); | |
File.destroy({ | |
avatarOf: null | |
createdAt: twelveHoursAgo | |
}).exec(function destroyedOrphans (err) { | |
if (err) { return done(err); } | |
// >> Anything else you want to do here << | |
return done(); | |
}); | |
})(function teardown(err){ | |
if (err) { | |
console.error('Job failed with error:',err); | |
console.error('(but continuing onwards to lower Sails...)'); | |
} | |
else { | |
console.log('Job completed successfully.'); | |
} | |
// Then, now that we're finished (error or not), call: | |
sails.lower(function afterLowering(err){ | |
if (err) { | |
console.error('Failed to lower Sails:',err); | |
return; | |
} | |
console.log('Successfully lowered Sails.'); | |
});//</callback from sails.lower() | |
});//<self-calling function | |
});//</callback from sails.load() | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment