src/corosio/src/detail/timer_service.hpp

100.0% Lines (7/7) 100.0% Functions (4/4)
src/corosio/src/detail/timer_service.hpp
Line Hits Source Code
1 //
2 // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // Official repository: https://github.com/cppalliance/corosio
8 //
9
10 #ifndef BOOST_COROSIO_SRC_DETAIL_TIMER_SERVICE_HPP
11 #define BOOST_COROSIO_SRC_DETAIL_TIMER_SERVICE_HPP
12
13 #include <boost/corosio/timer.hpp>
14 #include <boost/capy/ex/execution_context.hpp>
15
16 #include <chrono>
17 #include <cstddef>
18
19 namespace boost::corosio::detail {
20
21 struct scheduler;
22
23 class timer_service
24 : public capy::execution_context::service
25 , public io_object::io_service
26 {
27 public:
28 using clock_type = std::chrono::steady_clock;
29 using time_point = clock_type::time_point;
30
31 // Nested callback type - context + function pointer
32 class callback
33 {
34 void* ctx_ = nullptr;
35 void (*fn_)(void*) = nullptr;
36
37 public:
38 336 callback() = default;
39 336 callback(void* ctx, void (*fn)(void*)) noexcept : ctx_(ctx), fn_(fn) {}
40
41 explicit operator bool() const noexcept
42 {
43 return fn_ != nullptr;
44 }
45 8808 void operator()() const
46 {
47 8808 if (fn_)
48 8808 fn_(ctx_);
49 8808 }
50 };
51
52 // Query methods for scheduler
53 virtual bool empty() const noexcept = 0;
54 virtual time_point nearest_expiry() const noexcept = 0;
55
56 // Process expired timers - scheduler calls this after wait
57 virtual std::size_t process_expired() = 0;
58
59 // Callback for when earliest timer changes
60 virtual void set_on_earliest_changed(callback cb) = 0;
61
62 protected:
63 336 timer_service() = default;
64 };
65
66 // Get or create the timer service for the given context
67 timer_service&
68 get_timer_service(capy::execution_context& ctx, scheduler& sched);
69
70 } // namespace boost::corosio::detail
71
72 #endif
73