scheduler.h

main 84 lines · 2.2 KB Raw
Alex Alex Commit Server upload 18/10/2026 23:38
1/**
2 * The Forgotten Server - a free and open-source MMORPG server emulator
3 * Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20#ifndef FS_SCHEDULER_H_2905B3D5EAB34B4BA8830167262D2DC1
21#define FS_SCHEDULER_H_2905B3D5EAB34B4BA8830167262D2DC1
22
23#include "tasks.h"
24#include <unordered_set>
25#include <queue>
26
27#include "thread_holder_base.h"
28
29static constexpr int32_t SCHEDULER_MINTICKS = 50;
30
31class SchedulerTask : public Task
32{
33 public:
34 void setEventId(uint32_t id) {
35 eventId = id;
36 }
37 uint32_t getEventId() const {
38 return eventId;
39 }
40
41 std::chrono::system_clock::time_point getCycle() const {
42 return expiration;
43 }
44
45 private:
46 SchedulerTask(uint32_t delay, std::function<void (void)>&& f) : Task(delay, std::move(f)) {}
47
48 uint32_t eventId = 0;
49
50 friend SchedulerTask* createSchedulerTask(uint32_t, std::function<void (void)>);
51};
52
53SchedulerTask* createSchedulerTask(uint32_t delay, std::function<void (void)> f);
54
55struct TaskComparator {
56 bool operator()(const SchedulerTask* lhs, const SchedulerTask* rhs) const {
57 return lhs->getCycle() > rhs->getCycle();
58 }
59};
60
61class Scheduler : public ThreadHolder<Scheduler>
62{
63 public:
64 uint32_t addEvent(SchedulerTask* task);
65 bool stopEvent(uint32_t eventId);
66
67 void shutdown();
68
69 void threadMain();
70
71 private:
72 std::thread thread;
73 std::mutex eventLock;
74 std::condition_variable eventSignal;
75
76 uint32_t lastEventId {0};
77 std::priority_queue<SchedulerTask*, std::deque<SchedulerTask*>, TaskComparator> eventList;
78 std::unordered_set<uint32_t> eventIds;
79};
80
81extern Scheduler g_scheduler;
82
83#endif
84
Top