add jtk.timer module

This commit is contained in:
Josh Holtrop 2020-06-23 13:50:44 -04:00
parent 977b7cbf37
commit a811a743b8
2 changed files with 70 additions and 0 deletions

View File

@ -3,4 +3,5 @@ module jtk;
public import jtk.event;
public import jtk.init;
public import jtk.time;
public import jtk.timer;
public import jtk.window;

69
src/jtk/timer.d Normal file
View File

@ -0,0 +1,69 @@
module jtk.timer;
import jtk.time;
import std.algorithm;
class Timer
{
private static Timer[Timer] timers;
ulong next;
ulong interval;
void * user;
this(ulong delay, ulong interval, void * user)
{
ulong current_time = ms_time();
this.next = current_time + delay;
this.interval = interval;
this.user = user;
timers[this] = this;
}
void remove()
{
timers.remove(this);
}
void service()
{
if (this.interval == 0u)
{
remove();
}
else
{
this.next += this.interval;
}
}
static Timer get_expired_timer()
{
ulong current_time = ms_time();
foreach (Timer timer; timers)
{
if (timer.next <= current_time)
{
return timer;
}
}
return null;
}
static ulong time_to_next_timer_expiration()
{
ulong rv = cast(ulong)-1;
ulong current_time = ms_time();
foreach (Timer timer; timers)
{
if (timer.next <= current_time)
{
return 0u;
}
rv = min(rv, timer.next - current_time);
}
return rv;
}
}