Sese Framework  2.3.0
A cross-platform framework
Loading...
Searching...
No Matches
Timer.h
Go to the documentation of this file.
1// Copyright 2024 libsese
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
22#pragma once
23
24#include "sese/Config.h"
25#include "sese/thread/Thread.h"
26
27#include <atomic>
28#include <functional>
29#include <list>
30#include <mutex>
31
32namespace sese {
33
34class Timer;
36class TimerTask final : public std::enable_shared_from_this<TimerTask> {
37public:
38 friend class Timer;
39 using Ptr = std::shared_ptr<TimerTask>;
40
42 void cancel() noexcept;
43
44private:
45 // Private constructor
46 TimerTask() = default;
47 // Corresponding sleep duration
48 int64_t sleepTimestamp = 0;
49 // Corresponding target timestamp
50 int64_t targetTimestamp = 0;
51 // Whether to repeat
52 bool isRepeat = false;
53 // Timer callback function
54 std::function<void()> callback;
55 // Cancel callback function
56 std::function<void()> cancelCallback;
57};
58
60class Timer final : public std::enable_shared_from_this<Timer> {
61public:
62 using Ptr = std::shared_ptr<Timer>;
63
66 static Timer::Ptr create(size_t number = TIMER_WHEEL_NUMBER) noexcept;
68 ~Timer() noexcept;
69
75 TimerTask::Ptr delay(const std::function<void()> &callback, int64_t relative_timestamp, bool is_repeat = false) noexcept;
77 void shutdown() noexcept;
78
79public:
81 Timer() = default;
82 void loop() noexcept;
83 static void cancelCallback(const std::weak_ptr<Timer> &weak_timer, const std::weak_ptr<TimerTask> &weak_task) noexcept;
84
85 size_t number = 0;
86 std::mutex mutex{};
87 Thread::Ptr thread = nullptr;
88 std::atomic_bool isShutdown = false;
89 std::atomic<int64_t> currentTimestamp = 0;
90 std::list<TimerTask::Ptr> *timerTasks = nullptr;
91};
92} // namespace sese