1 module des.util.timer;
2 
3 import std.datetime;
4 import core.thread;
5 
6 struct TimerCallback
7 {
8     double time=0;
9     double tick=0;
10     void delegate() func;
11 
12     void reset() { time = 0; }
13     void update( double dt )
14     {  
15         time += dt;
16         if( time > tick )
17         {
18             time = 0;
19             if( func ) func();
20         }
21     }
22 }
23 
24 class Timer
25 {
26     StopWatch sw;
27     double time=0;
28     double all_time=0;
29     size_t cbindex=0;
30 
31     TimerCallback[string] callback;
32 
33     this() { sw.start(); }
34 
35     string every( double dt, void delegate() fnc )
36     { 
37         import std.string;
38         auto key = format( "__auto_gen_callback_%04d", cbindex++ );
39         callback[key] = TimerCallback( 0, dt, fnc ); 
40         return key;
41     }
42 
43     void every( double dt, string key, void delegate() fnc )
44     { callback[key] = TimerCallback( 0, dt, fnc ); }
45 
46     void removeCallback( string key )
47     { callback.remove(key); }
48 
49     double reset()
50     {
51         auto r = time;
52         time = 0;
53         foreach( cb; callback ) cb.reset();
54         return r;
55     }
56 
57     void restart( double s=0 )
58     {
59         cycle();
60         Thread.sleep( dur!"usecs"(cast(ulong)(s*1e6)) );
61     }
62 
63     double hardReset()
64     {
65         auto r = all_time;
66         all_time = 0;
67         reset();
68         return r;
69     }
70 
71     double cycle()
72     {
73         sw.stop();
74         auto dt = sw.peek().to!("seconds",double);
75         sw.reset();
76         sw.start();
77         time += dt;
78         all_time += dt;
79         foreach( cb; callback ) cb.update( dt );
80         return dt;
81     }
82 }