-
-
Notifications
You must be signed in to change notification settings - Fork 661
/
Copy pathtask.cpp
61 lines (48 loc) · 1.8 KB
/
task.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
61
/**
* Canary - A free and open-source MMORPG server emulator
* Copyright (©) 2019-2024 OpenTibiaBR <[email protected]>
* Repository: https://github.com/opentibiabr/canary
* License: https://github.com/opentibiabr/canary/blob/main/LICENSE
* Contributors: https://github.com/opentibiabr/canary/graphs/contributors
* Website: https://docs.opentibiabr.com/
*/
#include "pch.hpp"
#include "task.hpp"
#include "lib/logging/log_with_spd_log.hpp"
#include "lib/metrics/metrics.hpp"
std::atomic_uint_fast64_t Task::LAST_EVENT_ID = 0;
Task::Task(uint32_t expiresAfterMs, std::function<void(void)> &&f, std::string_view context) :
func(std::move(f)), context(context), utime(OTSYS_TIME()), expiration(expiresAfterMs > 0 ? OTSYS_TIME() + expiresAfterMs : 0) {
if (this->context.empty()) {
g_logger().error("[{}]: task context cannot be empty!", __FUNCTION__);
return;
}
assert(!this->context.empty() && "Context cannot be empty!");
}
Task::Task(std::function<void(void)> &&f, std::string_view context, uint32_t delay, bool cycle /* = false*/, bool log /*= true*/) :
func(std::move(f)), context(context), utime(OTSYS_TIME() + delay), delay(delay), cycle(cycle), log(log) {
if (this->context.empty()) {
g_logger().error("[{}]: task context cannot be empty!", __FUNCTION__);
return;
}
assert(!this->context.empty() && "Context cannot be empty!");
}
bool Task::execute() const {
metrics::task_latency measure(context);
if (isCanceled()) {
return false;
}
if (hasExpired()) {
g_logger().info("The task '{}' has expired, it has not been executed in {}.", getContext(), expiration - utime);
return false;
}
if (log) {
if (hasTraceableContext()) {
g_logger().trace("Executing task {}.", getContext());
} else {
g_logger().debug("Executing task {}.", getContext());
}
}
func();
return true;
}