title: How to run function after delay asynchronously in C++
body: <p>I want to implement something like Java's <code>TimerTask</code> in C++. I want to use it for invoking functions sometimes, not periodic. For periodic launching it will be a good idea to implement &quot;event loop&quot; scheme with 2 threads, with creating tasks in the first thread and process it in the second. But I do not want to write much code. So I've written smth like this:</p>
  <pre><code>template &lt;typename F, typename... Args&gt;
  auto timed_run(const uint64_t delay_ms, const F&amp; function, Args... args) {
    const auto f = [&amp;] {
      std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
      function(args...);
    };
  
    auto future = std::async(std::launch::async, f);
    return future;
  }
  </code></pre>
  <p>But it does not work as I need because it is not asynchronous at all due to it waits at future destructor as described <a href="https://en.cppreference.com/w/cpp/thread/async" rel="nofollow noreferrer">there</a>.</p>
  <p>So we need to create thread by ourselves. Okay, lets do it:</p>
  <pre><code>template &lt;typename F, typename... Args&gt;
  auto timed_run(const uint64_t delay_ms, const F&amp; function, Args... args) {
    std::packaged_task&lt;void()&gt; task([&amp;]() {
      std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
      function(args...);
    });
  
    auto future = task.get_future();
    std::thread thread(std::move(task));
    thread.detach();
  
    return future;
  }
  </code></pre>
  <p>In this implementation the are no locks and waits, but it simply does not run our function. It is because we can't use sleep on the detached threads.</p>
  <p>So, how can I implement what i want?</p>