cpp-msgpack-rpc 0.2.0
An RPC library implementing MessagePack RPC.
Loading...
Searching...
No Matches
timer.h
Go to the documentation of this file.
1/*
2 * Copyright 2023 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
20#pragma once
21
22#include <chrono>
23#include <memory>
24#include <utility>
25
26#include <asio/error_code.hpp>
27#include <asio/steady_timer.hpp>
28
31
32namespace msgpack_rpc::executors {
33
37class Timer {
38public:
45 Timer(const std::shared_ptr<IExecutor>& executor, OperationType type)
46 : timer_(executor->context(type)) {}
47
55 template <typename Function>
57 std::chrono::steady_clock::time_point time, Function&& function) {
58 timer_.expires_at(time);
59 timer_.async_wait([function_moved = std::forward<Function>(function)](
60 const asio::error_code& error) mutable {
61 if (!error) {
62 function_moved();
63 }
64 });
65 }
66
74 template <typename Function>
76 std::chrono::steady_clock::duration duration, Function&& function) {
77 timer_.expires_after(duration);
78 timer_.async_wait([function_moved = std::forward<Function>(function)](
79 const asio::error_code& error) mutable {
80 if (!error) {
81 function_moved();
82 }
83 });
84 }
85
89 void cancel() { timer_.cancel(); }
90
91private:
93 asio::steady_timer timer_;
94};
95
96} // namespace msgpack_rpc::executors
void cancel()
Cancel this timer.
Definition timer.h:89
asio::steady_timer timer_
Timer in asio library.
Definition timer.h:93
Timer(const std::shared_ptr< IExecutor > &executor, OperationType type)
Constructor.
Definition timer.h:45
void async_sleep_for(std::chrono::steady_clock::duration duration, Function &&function)
Asynchronously sleep for a duration.
Definition timer.h:75
void async_sleep_until(std::chrono::steady_clock::time_point time, Function &&function)
Asynchronously sleep until a time point.
Definition timer.h:56
Definition of IExecutor class.
Namespace of executors to process asynchronous tasks.
OperationType
Enumeration of types of operations.
Definition of OperationType enumeration.