-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.cpp
60 lines (50 loc) · 1.32 KB
/
timer.cpp
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
/*
* timer.cpp
*
* Created on 5 March 2015
* By: Synergiance
*/
/*
This class is designed to do everything time related, including delayed actions
*/
// Global Includes
#include <time.h>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <cctype>
#include <condition_variable>
#include <cstdlib> // atoi
// Local Includes
#include "timer.h"
#include "cmutex.h"
using namespace std;
cTimer::cTimer(CMutex& theQ)
{// Always initialize your variables to a value
stopping = false;
MessageQueue = &theQ;
}
cTimer::~cTimer()
{// Notify all threads to stop immediately
stopping = true;
cv.notify_all();
}
void cTimer::delayCommand(string duration, CMutexMessage event)
{// A command that can be delayed a certain amount of time in seconds
thread(&cTimer::timerThread, this, duration, event).detach();
}
void cTimer::timerThread(string duration, CMutexMessage event)
{// The thread that will take care of said command
unique_lock<mutex> lck(mtx);
char a = duration.back();
duration.pop_back();
int b = atoi(duration.c_str());
if (a == 'M')
cv.wait_for(lck, chrono::minutes(b));
else if (a == 'H')
cv.wait_for(lck, chrono::hours(b));
else if (a == 'S')
cv.wait_for(lck, chrono::seconds(b));
if (!stopping) MessageQueue->push(event);
}