simple.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // My non blocking main job
  2. var myjob = function(args,next) {
  3. // do nothing now but in 1 sec
  4. setTimeout(function() {
  5. // if i'm job id 10 or 20, let's add
  6. // another job dynamicaly in the queue.
  7. // It can be usefull for network operation (retry on timeout)
  8. if (args._jobId==10||args._jobId==20) {
  9. myQueueJobs.add(myjob,[999,'bla '+args._jobId]);
  10. }
  11. next();
  12. },Math.random(1000)*2000);
  13. }
  14. // Notice the "new" before require, to be able to use more
  15. // than one queue independently
  16. var myQueueJobs = new require('../qjobs')();
  17. // Let's add 30 job and add them to the queue
  18. for (var i = 0; i<30; i++) {
  19. myQueueJobs.add(myjob,[i,'test1']);
  20. }
  21. // I want to know when the first job has started
  22. myQueueJobs.on('start',function() {
  23. console.log('starting ...');
  24. console.log(JSON.stringify(myQueueJobs.stats()));
  25. });
  26. // I want to know when the last job has ended
  27. myQueueJobs.on('end',function() {
  28. clearInterval(statId);
  29. console.log('end');
  30. console.log(JSON.stringify(myQueueJobs.stats()));
  31. });
  32. // I want to know when each job has started
  33. myQueueJobs.on('jobStart',function(args) {
  34. console.log('jobStart',args);
  35. });
  36. // I want to know when each job has ended
  37. myQueueJobs.on('jobEnd',function(args) {
  38. console.log('jobEnd',args);
  39. // If i'm jobId 10, then make a pause of 5 sec
  40. if (args._jobId == 10) {
  41. myQueueJobs.pause(true);
  42. setTimeout(function() {
  43. myQueueJobs.pause(false);
  44. },5000);
  45. }
  46. });
  47. // I want to know if queue is in pause every sec
  48. myQueueJobs.on('pause',function(since) {
  49. console.log('in pause since '+since+' milliseconds');
  50. });
  51. // JOBS !! leeeeeeeeeet's staaaaaaaart !
  52. myQueueJobs.run();
  53. var statId = setInterval(function() {
  54. console.log(JSON.stringify(myQueueJobs.stats()));
  55. },1000);