timer.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2015 rain1017.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License. See the AUTHORS file
  14. // for names of contributors.
  15. 'use strict';
  16. var env = require('../env');
  17. var quick = require('../../lib');
  18. var P = quick.Promise;
  19. var logger = quick.logger.getLogger('test', __filename);
  20. describe('timer test', function(){
  21. beforeEach(env.initMemdbSync);
  22. afterEach(env.closeMemdbSync);
  23. it('timeout/interval', function(cb){
  24. var app = quick.mocks.app({serverId : 'area1', serverType : 'area'});
  25. var config = JSON.parse(JSON.stringify(env.memdbConfig)); //clone
  26. config.modelsPath = 'lib/mocks/models';
  27. app.set('memdbConfig', config);
  28. app.load(quick.components.memdb);
  29. app.load(quick.components.timer);
  30. return P.try(function(){
  31. return P.promisify(app.start, app)();
  32. })
  33. .then(function(){
  34. var deferred = P.defer();
  35. var Dummy = app.models.Dummy;
  36. app.timer.setInterval(function(){
  37. return P.try(function(){
  38. return Dummy.findByIdAsync(1);
  39. })
  40. .then(function(doc){
  41. if(!doc){
  42. doc = new Dummy({_id : 1, count : 0});
  43. }
  44. doc.count++;
  45. return doc.saveAsync();
  46. });
  47. }, 300, 'interval1');
  48. app.timer.setTimeout(function(){
  49. throw new Error('should not called');
  50. }, 700, 'timeout1');
  51. app.timer.setTimeout(function(){
  52. return P.try(function(){
  53. return Dummy.findByIdAsync(1);
  54. })
  55. .then(function(doc){
  56. doc.count.should.eql(2);
  57. return doc.removeAsync();
  58. })
  59. .then(function(){
  60. app.timer.clear('interval1');
  61. deferred.resolve();
  62. });
  63. }, 700, 'timeout1');
  64. var timeout = app.timer.setTimeout(function(){
  65. throw new Error('should not called');
  66. }, 200);
  67. clearTimeout(timeout);
  68. return deferred.promise;
  69. })
  70. .then(function(){
  71. return P.promisify(app.stop, app)();
  72. })
  73. .nodeify(cb);
  74. });
  75. });