1 module awebview.clock; 2 3 4 import std.datetime; 5 import std.container; 6 7 8 final class Timer 9 { 10 this() 11 { 12 _tasks = new typeof(_tasks)(); 13 } 14 15 16 void addTask(SysTime time, void delegate() task) 17 { 18 _tasks.insert(Task(time, task)); 19 } 20 21 22 void addTask(Duration delay, void delegate() task) 23 { 24 addTask(Clock.currTime + delay, task); 25 } 26 27 28 void addRepeatTask(Duration delay, Duration interval, ulong times, void delegate() task) 29 { 30 static struct T 31 { 32 Duration interval; 33 ulong times; 34 void delegate() task; 35 Timer timer; 36 37 void call() 38 { 39 task(); 40 --times; 41 if(times > 0) 42 timer.addTask(interval, &call); 43 } 44 } 45 46 T t; 47 t.interval = interval; 48 t.times = times; 49 t.task = task; 50 t.timer = this; 51 52 addTask(delay, &(t.call)); 53 } 54 55 56 void onUpdate() 57 { 58 while(!_tasks.empty && _tasks.front.t < Clock.currTime){ 59 auto dg = _tasks.front.task; 60 _tasks.removeFront(); 61 dg(); 62 } 63 } 64 65 66 private: 67 static struct Task 68 { 69 SysTime t; 70 void delegate() task; 71 } 72 73 private: 74 RedBlackTree!(Task, "a.t < b.t") _tasks; 75 } 76 77 78 79 final class TimeSchedular(T) 80 { 81 import std.container; 82 import std.typecons; 83 84 private 85 { 86 alias Dg = void delegate(); 87 } 88 89 this() 90 { 91 _tasks = new typeof(_tasks)(); 92 } 93 94 95 void opIndexAssign(Dg dg, T time) 96 { 97 _tasks.insert(tuple(time, dg)); 98 } 99 100 101 void update(T time) 102 { 103 while(!_tasks.empty && _tasks.front[0] < time){ 104 _tasks.front[1](); 105 _tasks.removeFront(); 106 } 107 } 108 109 110 void clear() 111 { 112 _tasks.clear(); 113 } 114 115 private: 116 RedBlackTree!(Tuple!(T, Dg), "a[0] < b[0]") _tasks; 117 }