|
| 1 | +// Copyright 2025 Brad Martin |
| 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 | + |
| 15 | +#ifndef RCLPY__EVENTS_EXECUTOR__DELAYED_EVENT_THREAD_HPP_ |
| 16 | +#define RCLPY__EVENTS_EXECUTOR__DELAYED_EVENT_THREAD_HPP_ |
| 17 | + |
| 18 | +#include <chrono> |
| 19 | +#include <condition_variable> |
| 20 | +#include <functional> |
| 21 | +#include <mutex> |
| 22 | +#include <thread> |
| 23 | + |
| 24 | +#include "events_executor/events_queue.hpp" |
| 25 | + |
| 26 | +namespace rclpy |
| 27 | +{ |
| 28 | +namespace events_executor |
| 29 | +{ |
| 30 | + |
| 31 | +/// This object manages posting an event handler to an EventsQueue after a specified delay. The |
| 32 | +/// current delay may be changed or canceled at any time. This is done by way of a self-contained |
| 33 | +/// child thread to perform the wait. |
| 34 | +class DelayedEventThread |
| 35 | +{ |
| 36 | +public: |
| 37 | + /// The pointer is aliased and must live for the lifetime of this object. |
| 38 | + explicit DelayedEventThread(EventsQueue *); |
| 39 | + ~DelayedEventThread(); |
| 40 | + |
| 41 | + /// Schedules an event handler to be enqueued at the specified time point. Replaces any previous |
| 42 | + /// wait and handler, which will never be dispatched if it has not been already. |
| 43 | + void EnqueueAt(std::chrono::steady_clock::time_point when, std::function<void()> handler); |
| 44 | + |
| 45 | + /// Cancels any previously-scheduled handler. |
| 46 | + void Cancel() {EnqueueAt({}, {});} |
| 47 | + |
| 48 | +private: |
| 49 | + void RunThread(); |
| 50 | + |
| 51 | + EventsQueue * const events_queue_; |
| 52 | + std::mutex mutex_; |
| 53 | + bool done_{}; |
| 54 | + std::condition_variable cv_; |
| 55 | + std::chrono::steady_clock::time_point when_; |
| 56 | + std::function<void()> handler_; |
| 57 | + std::thread thread_; |
| 58 | +}; |
| 59 | + |
| 60 | +} // namespace events_executor |
| 61 | +} // namespace rclpy |
| 62 | + |
| 63 | +#endif // RCLPY__EVENTS_EXECUTOR__DELAYED_EVENT_THREAD_HPP_ |
0 commit comments