1//! @file time.cpp
2//! @author ryftchen
3//! @brief The definitions (time) in the utility module.
4//! @version 0.1.0
5//! @copyright Copyright (c) 2022-2025 ryftchen. All rights reserved.
6
7#include "time.hpp"
8
9#include <chrono>
10
11namespace utility::time
12{
13//! @brief Function version number.
14//! @return version number (major.minor.patch)
15const char* version() noexcept
16{
17 static const char* const ver = "0.1.0";
18 return ver;
19}
20
21Timer::~Timer()
22{
23 stop();
24}
25
26void Timer::start(const std::chrono::milliseconds& interval, const bool isPeriodic)
27{
28 if (isRunning())
29 {
30 return;
31 }
32
33 worker = std::jthread(
34 [this, interval, isPeriodic](const std::stop_token& token)
35 {
36 std::unique_lock<std::mutex> lock(mtx);
37 if (const auto waitTimeout = [this, interval, &token](std::unique_lock<std::mutex>& lock)
38 { return !cond.wait_for(lock&: lock, rtime: interval, p: [&token]() { return token.stop_requested(); }); };
39 !isPeriodic)
40 {
41 if (waitTimeout(lock) && callback)
42 {
43 callback();
44 }
45 }
46 else
47 {
48 while (waitTimeout(lock) && callback)
49 {
50 callback();
51 }
52 }
53 });
54}
55
56void Timer::stop()
57{
58 if (!isRunning())
59 {
60 return;
61 }
62
63 worker.request_stop();
64 cond.notify_all();
65 if (worker.joinable())
66 {
67 worker.join();
68 }
69}
70
71bool Timer::isRunning() const
72{
73 return worker.joinable();
74}
75
76Stopwatch::Stopwatch()
77{
78 reset();
79}
80
81void Stopwatch::reset()
82{
83 beginTime = std::chrono::high_resolution_clock::now();
84}
85
86//! @brief Get the current standard time (ISO 8601), like "1970-01-01T00:00:00.000000000Z".
87//! @return current standard time
88std::string currentStandardTime()
89{
90 return std::format(fmt: "{:%FT%TZ}", args: std::chrono::system_clock::now());
91}
92} // namespace utility::time
93