| 346 | |
| 347 | |
| 348 | Try<Nothing> EventLoop::launchTimer( |
| 349 | const Duration& duration, const lambda::function<void()>& callback) |
| 350 | { |
| 351 | // Create a non-inheritable, manual reset, unnamed timer. |
| 352 | HANDLE timer = ::CreateWaitableTimerW(nullptr, true, nullptr); |
| 353 | if (timer == nullptr) { |
| 354 | return WindowsError(); |
| 355 | } |
| 356 | |
| 357 | // If you give a positive value, then the timer call interprets it as |
| 358 | // absolute time. A negative value is interpretted as relative time. |
| 359 | // 0 is run immediately. The resolution is in 100ns. |
| 360 | LARGE_INTEGER time_elapsed; |
| 361 | time_elapsed.QuadPart = -duration.ns() / 100; |
| 362 | |
| 363 | TimerOverlapped* overlapped = |
| 364 | new TimerOverlapped{timer, time_elapsed, callback}; |
| 365 | |
| 366 | // We don't actually set the timer here since APCs only execute in the same |
| 367 | // thread that called the async function. So, we queue the function call to |
| 368 | // the IOCP so the event loop thread can queue the APC. |
| 369 | // |
| 370 | // NOTE: `::PostQueuedCompletionStatus` does not process the second to fourth |
| 371 | // arguments, so you can give anything for them. Specifically, the overlapped |
| 372 | // parameter doesn't need to point to a `OVERLAPPED` structure. See |
| 373 | // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365458(v=vs.85).aspx // NOLINT(whitespace/line_length) |
| 374 | const BOOL success = ::PostQueuedCompletionStatus( |
| 375 | iocp_handle_.get(), |
| 376 | 0, |
| 377 | KEY_TIMER, |
| 378 | reinterpret_cast<OVERLAPPED*>(overlapped)); |
| 379 | |
| 380 | if (!success) { |
| 381 | // Failing `PostQueuedCompletionStatus` means we have to clean the |
| 382 | // memory here, since the APC won't execute. |
| 383 | WindowsError error; |
| 384 | delete overlapped; |
| 385 | ::CloseHandle(timer); |
| 386 | return error; |
| 387 | } |
| 388 | |
| 389 | // The APC callback will clean up the memory and handle, so we can return. |
| 390 | return Nothing(); |
| 391 | } |
| 392 | |
| 393 | |
| 394 | // NOTE: The following functions use `int_fd` instead of the native Win32 |