job.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * This is the class of the job used in schedule module
  3. */
  4. var cronTrigger = require('./cronTrigger');
  5. var simpleTrigger = require('./simpleTrigger');
  6. var jobId = 1;
  7. var SIMPLE_JOB = 1;
  8. var CRON_JOB = 2;
  9. var jobCount = 0;
  10. var warnLimit = 500;
  11. var logger = require('log4js').getLogger(__filename);
  12. //For test
  13. var lateCount = 0;
  14. var Job = function(trigger, jobFunc, jobData){
  15. this.data = (!!jobData)?jobData:null;
  16. this.func = jobFunc;
  17. if(typeof(trigger) == 'string'){
  18. this.type = CRON_JOB;
  19. this.trigger = cronTrigger.createTrigger(trigger, this);
  20. }else if(typeof(trigger) == 'object'){
  21. this.type = SIMPLE_JOB;
  22. this.trigger = simpleTrigger.createTrigger(trigger, this);
  23. }
  24. this.id = jobId++;
  25. this.runTime = 0;
  26. };
  27. var pro = Job.prototype;
  28. /**
  29. * Run the job code
  30. */
  31. pro.run = function(){
  32. try{
  33. jobCount++;
  34. this.runTime++;
  35. var late = Date.now() - this.excuteTime();
  36. if(late>warnLimit)
  37. logger.warn('run Job count ' + jobCount + ' late :' + late + ' lateCount ' + (++lateCount));
  38. this.func(this.data);
  39. }catch(e){
  40. logger.error("Job run error for exception ! " + e.stack());
  41. }
  42. };
  43. /**
  44. * Compute the next excution time
  45. */
  46. pro.nextTime = function(){
  47. return this.trigger.nextExcuteTime();
  48. };
  49. pro.excuteTime = function(){
  50. return this.trigger.excuteTime();
  51. };
  52. /**
  53. * The Interface to create Job
  54. * @param trigger The trigger to use
  55. * @param jobFunc The function the job to run
  56. * @param jobDate The date the job use
  57. * @return The new instance of the give job or null if fail
  58. */
  59. function createJob(trigger, jobFunc, jobData){
  60. return new Job(trigger, jobFunc, jobData);
  61. }
  62. module.exports.createJob = createJob;