| 263 | |
| 264 | |
| 265 | Timer Clock::timer( |
| 266 | const Duration& duration, |
| 267 | const lambda::function<void()>& thunk) |
| 268 | { |
| 269 | // Start at 1 since Timer() instances use id 0. |
| 270 | static std::atomic<uint64_t> id(1); |
| 271 | |
| 272 | // Assumes Clock::now() does Clock::now(__process__). |
| 273 | Timeout timeout = Timeout::in(duration); |
| 274 | |
| 275 | UPID pid = __process__ != nullptr ? __process__->self() : UPID(); |
| 276 | |
| 277 | Timer timer(id.fetch_add(1), timeout, pid, thunk); |
| 278 | |
| 279 | VLOG(3) << "Created a timer for " << pid << " in " << stringify(duration) |
| 280 | << " in the future (" << timeout.time() << ")"; |
| 281 | |
| 282 | // Add the timer. |
| 283 | synchronized (timers_mutex) { |
| 284 | if (timers->size() == 0 || |
| 285 | timer.timeout().time() < timers->begin()->first) { |
| 286 | // Need to interrupt the loop to update/set timer repeat. |
| 287 | (*timers)[timer.timeout().time()].push_back(timer); |
| 288 | |
| 289 | // Schedule another "tick" if necessary. |
| 290 | clock::scheduleTick(*timers, clock::ticks); |
| 291 | } else { |
| 292 | // Timer repeat is adequate, just add the timeout. |
| 293 | CHECK(timers->size() >= 1); |
| 294 | (*timers)[timer.timeout().time()].push_back(timer); |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | return timer; |
| 299 | } |
| 300 | |
| 301 | |
| 302 | bool Clock::cancel(const Timer& timer) |