-
Notifications
You must be signed in to change notification settings - Fork 2
/
timer.h
65 lines (52 loc) · 1010 Bytes
/
timer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#pragma once
#include <tr1/functional>
#include <unistd.h>
#include "thread.h"
using namespace std;
using namespace tr1;
using namespace placeholders; //for bind
class Timer {
Thread thread;
bool destruct;
function<void()> callback;
double timeout;
void waiter(){
sleep((int)timeout);
usleep((int)((timeout - (int)timeout)*1000000));
callback();
}
void nullcallback(){ }
public:
Timer() {
timeout = 0;
destruct = false;
callback = bind(&Timer::nullcallback, this);
}
Timer(double time, function<void()> fn){
destruct = false;
set(time, fn);
}
void set(double time, function<void()> fn){
cancel();
timeout = time;
callback = fn;
if(time < 0.001){ //too small, just call it directly
destruct = false;
fn();
}else{
destruct = true;
thread(bind(&Timer::waiter, this));
}
}
void cancel(){
if(destruct){
destruct = false;
callback = bind(&Timer::nullcallback, this);
thread.cancel();
thread.join();
}
}
~Timer(){
cancel();
}
};