2
0

Timer.hx 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /*
  2. * Copyright (C)2005-2018 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package haxe;
  23. /**
  24. The Timer class allows you to create asynchronous timers on platforms that
  25. support events.
  26. The intended usage is to create an instance of the Timer class with a given
  27. interval, set its run() method to a custom function to be invoked and
  28. eventually call stop() to stop the Timer.
  29. Note that a running Timer may or may not prevent the program to exit
  30. automatically when main() returns.
  31. It is also possible to extend this class and override its run() method in
  32. the child class.
  33. **/
  34. class Timer {
  35. #if (flash || js)
  36. private var id : Null<Int>;
  37. #elseif java
  38. private var timer : java.util.Timer;
  39. private var task : java.util.TimerTask;
  40. #else
  41. private var event : MainLoop.MainEvent;
  42. #end
  43. /**
  44. Creates a new timer that will run every `time_ms` milliseconds.
  45. After creating the Timer instance, it calls `this.run` repeatedly,
  46. with delays of `time_ms` milliseconds, until `this.stop` is called.
  47. The first invocation occurs after `time_ms` milliseconds, not
  48. immediately.
  49. The accuracy of this may be platform-dependent.
  50. **/
  51. public function new( time_ms : Int ){
  52. #if flash
  53. var me = this;
  54. id = untyped __global__["flash.utils.setInterval"](function() { me.run(); },time_ms);
  55. #elseif js
  56. var me = this;
  57. id = untyped setInterval(function() me.run(),time_ms);
  58. #elseif java
  59. timer = new java.util.Timer();
  60. timer.scheduleAtFixedRate(task = new TimerTask(this), haxe.Int64.ofInt(time_ms), haxe.Int64.ofInt(time_ms));
  61. #else
  62. var dt = time_ms / 1000;
  63. event = MainLoop.add(function() {
  64. @:privateAccess event.nextRun += dt;
  65. run();
  66. });
  67. event.delay(dt);
  68. #end
  69. }
  70. /**
  71. Stops `this` Timer.
  72. After calling this method, no additional invocations of `this.run`
  73. will occur.
  74. It is not possible to restart `this` Timer once stopped.
  75. **/
  76. public function stop() {
  77. #if (flash || js)
  78. if( id == null )
  79. return;
  80. #if flash
  81. untyped __global__["flash.utils.clearInterval"](id);
  82. #elseif js
  83. untyped clearInterval(id);
  84. #end
  85. id = null;
  86. #elseif java
  87. if(timer != null) {
  88. timer.cancel();
  89. timer = null;
  90. }
  91. task = null;
  92. #else
  93. if( event != null ) {
  94. event.stop();
  95. event = null;
  96. }
  97. #end
  98. }
  99. /**
  100. This method is invoked repeatedly on `this` Timer.
  101. It can be overridden in a subclass, or rebound directly to a custom
  102. function:
  103. var timer = new haxe.Timer(1000); // 1000ms delay
  104. timer.run = function() { ... }
  105. Once bound, it can still be rebound to different functions until `this`
  106. Timer is stopped through a call to `this.stop`.
  107. **/
  108. public dynamic function run() {
  109. }
  110. /**
  111. Invokes `f` after `time_ms` milliseconds.
  112. This is a convenience function for creating a new Timer instance with
  113. `time_ms` as argument, binding its run() method to `f` and then stopping
  114. `this` Timer upon the first invocation.
  115. If `f` is null, the result is unspecified.
  116. **/
  117. public static function delay( f : Void -> Void, time_ms : Int ) {
  118. var t = new haxe.Timer(time_ms);
  119. t.run = function() {
  120. t.stop();
  121. f();
  122. };
  123. return t;
  124. }
  125. /**
  126. Measures the time it takes to execute `f`, in seconds with fractions.
  127. This is a convenience function for calculating the difference between
  128. Timer.stamp() before and after the invocation of `f`.
  129. The difference is passed as argument to Log.trace(), with "s" appended
  130. to denote the unit. The optional `pos` argument is passed through.
  131. If `f` is null, the result is unspecified.
  132. **/
  133. public static function measure<T>( f : Void -> T, ?pos : PosInfos ) : T {
  134. var t0 = stamp();
  135. var r = f();
  136. Log.trace((stamp() - t0) + "s", pos);
  137. return r;
  138. }
  139. /**
  140. Returns a timestamp, in seconds with fractions.
  141. The value itself might differ depending on platforms, only differences
  142. between two values make sense.
  143. **/
  144. public static inline function stamp() : Float {
  145. #if flash
  146. return flash.Lib.getTimer() / 1000;
  147. #elseif (neko || php)
  148. return Sys.time();
  149. #elseif js
  150. return Date.now().getTime() / 1000;
  151. #elseif cpp
  152. return untyped __global__.__time_stamp();
  153. #elseif python
  154. return Sys.cpuTime();
  155. #elseif sys
  156. return Sys.time();
  157. #else
  158. return 0;
  159. #end
  160. }
  161. }
  162. #if java
  163. @:nativeGen
  164. private class TimerTask extends java.util.TimerTask {
  165. var timer:Timer;
  166. public function new(timer:Timer):Void {
  167. super();
  168. this.timer = timer;
  169. }
  170. @:overload override public function run():Void {
  171. timer.run();
  172. }
  173. }
  174. #end