1 /* Timer stuff.
2  *
3  * (C) 2003-2020 Anope Team
4  * Contact us at team@anope.org
5  *
6  * Please read COPYING and README for further details.
7  */
8 
9 #include "services.h"
10 #include "timers.h"
11 
12 std::multimap<time_t, Timer *> TimerManager::Timers;
13 
Timer(long time_from_now,time_t now,bool repeating)14 Timer::Timer(long time_from_now, time_t now, bool repeating)
15 {
16 	owner = NULL;
17 	trigger = now + time_from_now;
18 	secs = time_from_now;
19 	repeat = repeating;
20 	settime = now;
21 
22 	TimerManager::AddTimer(this);
23 }
24 
Timer(Module * creator,long time_from_now,time_t now,bool repeating)25 Timer::Timer(Module *creator, long time_from_now, time_t now, bool repeating)
26 {
27 	owner = creator;
28 	trigger = now + time_from_now;
29 	secs = time_from_now;
30 	repeat = repeating;
31 	settime = now;
32 
33 	TimerManager::AddTimer(this);
34 }
35 
~Timer()36 Timer::~Timer()
37 {
38 	TimerManager::DelTimer(this);
39 }
40 
SetTimer(time_t t)41 void Timer::SetTimer(time_t t)
42 {
43 	TimerManager::DelTimer(this);
44 	trigger = t;
45 	TimerManager::AddTimer(this);
46 }
47 
GetTimer() const48 time_t Timer::GetTimer() const
49 {
50 	return trigger;
51 }
52 
GetRepeat() const53 bool Timer::GetRepeat() const
54 {
55 	return repeat;
56 }
57 
GetSetTime() const58 time_t Timer::GetSetTime() const
59 {
60 	return settime;
61 }
62 
SetSecs(time_t t)63 void Timer::SetSecs(time_t t)
64 {
65 	TimerManager::DelTimer(this);
66 	secs = t;
67 	trigger = Anope::CurTime + t;
68 	TimerManager::AddTimer(this);
69 }
70 
GetSecs() const71 long Timer::GetSecs() const
72 {
73 	return secs;
74 }
75 
GetOwner() const76 Module *Timer::GetOwner() const
77 {
78 	return owner;
79 }
80 
AddTimer(Timer * t)81 void TimerManager::AddTimer(Timer *t)
82 {
83 	Timers.insert(std::make_pair(t->GetTimer(), t));
84 }
85 
DelTimer(Timer * t)86 void TimerManager::DelTimer(Timer *t)
87 {
88 	std::pair<std::multimap<time_t, Timer *>::iterator, std::multimap<time_t, Timer *>::iterator> itpair = Timers.equal_range(t->GetTimer());
89 	for (std::multimap<time_t, Timer *>::iterator i = itpair.first; i != itpair.second; ++i)
90 	{
91 		if (i->second == t)
92 		{
93 			Timers.erase(i);
94 			break;
95 		}
96 	}
97 }
98 
TickTimers(time_t ctime)99 void TimerManager::TickTimers(time_t ctime)
100 {
101 	while (!Timers.empty())
102 	{
103 		std::multimap<time_t, Timer *>::iterator it = Timers.begin();
104 		Timer *t = it->second;
105 
106 		if (t->GetTimer() > ctime)
107 			break;
108 
109 		t->Tick(ctime);
110 
111 		if (t->GetRepeat())
112 			t->SetTimer(ctime + t->GetSecs());
113 		else
114 			delete t;
115 	}
116 }
117 
DeleteTimersFor(Module * m)118 void TimerManager::DeleteTimersFor(Module *m)
119 {
120 	for (std::multimap<time_t, Timer *>::iterator it = Timers.begin(), it_next = it; it != Timers.end(); it = it_next)
121 	{
122 		++it_next;
123 		if (it->second->GetOwner() == m)
124 			delete it->second;
125 	}
126 }
127