Provides an abstraction over `Timer` and `Clock::timer` that completes a future after some duration and lets you attempt to discard that future. This can be used along with `loop` to create "waiting loops", for example: // Wait until a file exists, check for it ever every second. loop(None(), []() { return after(Seconds(1)); }, [=]() { if (os::exists(file)) -> ControlFlow { return Break
| 43 | // return Continue(); |
| 44 | // }); |
| 45 | inline Future<Nothing> after(const Duration& duration) |
| 46 | { |
| 47 | std::shared_ptr<Promise<Nothing>> promise(new Promise<Nothing>()); |
| 48 | |
| 49 | Timer timer = Clock::timer(duration, [=]() { |
| 50 | promise->set(Nothing()); |
| 51 | }); |
| 52 | |
| 53 | // Attempt to discard the promise if the future is discarded. |
| 54 | // |
| 55 | // NOTE: while the future holds a reference to the promise there is |
| 56 | // no cicular reference here because even if there are no references |
| 57 | // to the Future the timer will eventually fire and we'll set the |
| 58 | // promise which will clear the `onDiscard` callback and delete the |
| 59 | // reference to Promise. |
| 60 | promise->future() |
| 61 | .onDiscard([=]() { |
| 62 | if (Clock::cancel(timer)) { |
| 63 | promise->discard(); |
| 64 | } |
| 65 | }); |
| 66 | |
| 67 | return promise->future(); |
| 68 | } |
| 69 | |
| 70 | } // namespace process { |
| 71 |