-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScheduler.h
102 lines (85 loc) · 2.42 KB
/
Scheduler.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#pragma once
#include"RxConcurrent/CommonDefines.h"
namespace BaseLib { namespace Concurrent {
template <typename Pool, typename S = std::shared_ptr<Templates::Schedulable<Duration>>>
class Scheduler
: public BaseLib::Runnable
, public Templates::FinalizeMethod
, public Templates::ReactorMethods<bool, Duration, BaseLib::GeneralException>
, public Templates::LockableType<Scheduler<Pool>>
{
typedef MutexTypeLocker<Scheduler<Pool, S>> Locker;
public:
Scheduler(Pool pool, S schedulable)
: schedulable_(schedulable)
, pool_(pool)
{ }
virtual ~Scheduler()
{ }
virtual void run()
{
S schedulable = getSchedulableSecurely();
if(schedulable != nullptr)
{
schedule<Duration>(this, schedulable, pool_);
}
else
{
IINFO() << "Schedulable went out of scope. Shutting down....";
pool_->Complete(this);
}
}
virtual bool Next(Duration timeMs)
{
return pool_->Next(this, timeMs);
}
virtual bool Error(BaseLib::GeneralException exception)
{
return pool_->Error(this, exception);
}
virtual bool Complete()
{
return pool_->Complete(this);
}
virtual bool Finalize()
{
Locker lock(this);
schedulable_ = nullptr;
return true;
}
private:
// -----------------------------------------------------------
// private implementation
// -----------------------------------------------------------
S getSchedulableSecurely() const
{
Locker lock(this);
return schedulable_;
}
template <typename T>
static void schedule(Scheduler* scheduler, S schedulable, Pool pool)
{
try
{
schedulable->run();
if(schedulable->HasNext())
{
T waitTimeMs = schedulable->Next();
pool->Next(scheduler, waitTimeMs); // == onNext(Pair<Runnable, Long>(this, waitTimeMs))
}
else
{
pool->Complete(scheduler);
}
}
catch(BaseLib::GeneralException throwable)
{
IWARNING() << "Stopping schedulable. Caught unhandled exception " << throwable.msg();
pool->Error(scheduler, throwable); // == onError(Pair<Runnable, Throwable>(this, throwable));
}
}
private:
S schedulable_;
Pool pool_;
};
}}