blob: ba5ba7837220616dcd4135477d10f1c08ff355e0 (
plain)
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
|
#include "scheduled_task.hpp"
#include "timer.hpp"
ScheduledTask::Routine::Routine(fn_t const & fn,
unsigned ms,
threads::Condition * cond)
: m_fn(fn),
m_ms(ms),
m_pCond(cond)
{}
void ScheduledTask::Routine::Do()
{
m_pCond->Lock();
unsigned msLeft = m_ms;
while (!IsCancelled())
{
my::Timer t;
if (m_pCond->Wait(msLeft))
break;
msLeft -= (unsigned)(t.ElapsedSeconds() * 1000);
}
if (!IsCancelled())
m_fn();
m_pCond->Unlock();
}
void ScheduledTask::Routine::Cancel()
{
threads::IRoutine::Cancel();
m_pCond->Signal();
m_pCond->Unlock();
}
ScheduledTask::ScheduledTask(fn_t const & fn, unsigned ms)
: m_routine(new Routine(fn, ms, &m_cond))
{
m_thread.Create(m_routine.get());
}
bool ScheduledTask::CancelNoBlocking()
{
if (m_cond.TryLock())
{
m_thread.Cancel();
return true;
}
return false;
}
void ScheduledTask::CancelBlocking()
{
m_cond.Lock();
m_thread.Cancel();
}
|