Timer.hx 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. /*
  2. * Copyright (C)2005-2019 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. #if (target.threaded && !cppia)
  24. import sys.thread.Thread;
  25. import sys.thread.EventLoop;
  26. #end
  27. /**
  28. The `Timer` class allows you to create asynchronous timers on platforms that
  29. support events.
  30. The intended usage is to create an instance of the `Timer` class with a given
  31. interval, set its `run()` method to a custom function to be invoked and
  32. eventually call `stop()` to stop the `Timer`.
  33. Note that a running `Timer` may or may not prevent the program to exit
  34. automatically when `main()` returns.
  35. It is also possible to extend this class and override its `run()` method in
  36. the child class.
  37. Notice for threaded targets:
  38. `Timer` instances require threads they were created in to run with Haxe's event loops.
  39. Main thread of a Haxe program always contains an event loop. For other cases use
  40. `sys.thread.Thread.createWithEventLoop` and `sys.thread.Thread.runWithEventLoop` methods.
  41. **/
  42. class Timer {
  43. #if (flash || js)
  44. private var id:Null<Int>;
  45. #elseif (target.threaded && !cppia)
  46. var thread:Thread;
  47. var eventHandler:EventHandler;
  48. #else
  49. private var event:MainLoop.MainEvent;
  50. #end
  51. /**
  52. Creates a new timer that will run every `time_ms` milliseconds.
  53. After creating the Timer instance, it calls `this.run` repeatedly,
  54. with delays of `time_ms` milliseconds, until `this.stop` is called.
  55. The first invocation occurs after `time_ms` milliseconds, not
  56. immediately.
  57. The accuracy of this may be platform-dependent.
  58. **/
  59. public function new(time_ms:Int) {
  60. #if flash
  61. var me = this;
  62. id = untyped __global__["flash.utils.setInterval"](function() {
  63. me.run();
  64. }, time_ms);
  65. #elseif js
  66. var me = this;
  67. id = untyped setInterval(function() me.run(), time_ms);
  68. #elseif (target.threaded && !cppia)
  69. thread = Thread.current();
  70. eventHandler = thread.events.repeat(() -> this.run(), time_ms);
  71. #else
  72. var dt = time_ms / 1000;
  73. event = MainLoop.add(function() {
  74. @:privateAccess event.nextRun += dt;
  75. run();
  76. });
  77. event.delay(dt);
  78. #end
  79. }
  80. /**
  81. Stops `this` Timer.
  82. After calling this method, no additional invocations of `this.run`
  83. will occur.
  84. It is not possible to restart `this` Timer once stopped.
  85. **/
  86. public function stop() {
  87. #if (flash || js)
  88. if (id == null)
  89. return;
  90. #if flash
  91. untyped __global__["flash.utils.clearInterval"](id);
  92. #elseif js
  93. untyped clearInterval(id);
  94. #end
  95. id = null;
  96. #elseif (target.threaded && !cppia)
  97. thread.events.cancel(eventHandler);
  98. #else
  99. if (event != null) {
  100. event.stop();
  101. event = null;
  102. }
  103. #end
  104. }
  105. /**
  106. This method is invoked repeatedly on `this` Timer.
  107. It can be overridden in a subclass, or rebound directly to a custom
  108. function:
  109. ```haxe
  110. var timer = new haxe.Timer(1000); // 1000ms delay
  111. timer.run = function() { ... }
  112. ```
  113. Once bound, it can still be rebound to different functions until `this`
  114. Timer is stopped through a call to `this.stop`.
  115. **/
  116. public dynamic function run() {}
  117. /**
  118. Invokes `f` after `time_ms` milliseconds.
  119. This is a convenience function for creating a new Timer instance with
  120. `time_ms` as argument, binding its `run()` method to `f` and then stopping
  121. `this` Timer upon the first invocation.
  122. If `f` is `null`, the result is unspecified.
  123. **/
  124. public static function delay(f:Void->Void, time_ms:Int) {
  125. var t = new haxe.Timer(time_ms);
  126. t.run = function() {
  127. t.stop();
  128. f();
  129. };
  130. return t;
  131. }
  132. /**
  133. Measures the time it takes to execute `f`, in seconds with fractions.
  134. This is a convenience function for calculating the difference between
  135. `Timer.stamp()` before and after the invocation of `f`.
  136. The difference is passed as argument to `Log.trace()`, with `"s"` appended
  137. to denote the unit. The optional `pos` argument is passed through.
  138. If `f` is `null`, the result is unspecified.
  139. **/
  140. public static function measure<T>(f:Void->T, ?pos:PosInfos):T {
  141. var t0 = stamp();
  142. var r = f();
  143. Log.trace((stamp() - t0) + "s", pos);
  144. return r;
  145. }
  146. /**
  147. Returns a timestamp, in seconds with fractions.
  148. The value itself might differ depending on platforms, only differences
  149. between two values make sense.
  150. **/
  151. public static inline function stamp():Float {
  152. #if flash
  153. return flash.Lib.getTimer() / 1000;
  154. #elseif js
  155. #if nodejs
  156. var hrtime = js.Syntax.code('process.hrtime()'); // [seconds, remaining nanoseconds]
  157. return hrtime[0] + hrtime[1] / 1e9;
  158. #else
  159. return @:privateAccess HxOverrides.now() / 1000;
  160. #end
  161. #elseif cpp
  162. return untyped __global__.__time_stamp();
  163. #elseif python
  164. return Sys.cpuTime();
  165. #elseif sys
  166. return Sys.time();
  167. #else
  168. return 0;
  169. #end
  170. }
  171. }