title: Accurate continuous timer callback
body: <p>Ive got an application where I want to display a frame every x milliseconds. </p>
  
  <p>Previously I did it like this:</p>
  
  <pre><code>class SomeClass
  {
      boost::thread thread_;
      boost::timer timer_;
  public:
      SomeClass() : thread_([=]{Display();}) 
      {
      }
  
      void Display
      {    
          double wait = 1.0/fps*1000.0;    
          while(isRunning_)
          {
               double elapsed = timer.elapsed()*1000.0;
               if(elapsed &lt; wait) 
                    boost::this_thread::sleep(boost::posix_time::milliseconds(static_cast&lt;unsigned int&gt;(wait - elapsed)));
               timer.restart();
  
               // ... Get Frame. This can block while no frames are being rendered.
  
               // ... Display Frame.
        }
      }
  }
  </code></pre>
  
  <p>However I dont think solution has very good accuracy. I might be wrong?</p>
  
  <p>I was hoping to used boost::asio::deadline_timer instead, but I'm unsure how to use it.</p>
  
  <p>This is what ive tried, which doesn't seem to wait at all. It seems to just render the frames as fast as it can.</p>
  
  <pre><code>class SomeClass
      {
          boost::thread thread_;
          boost::asio::io_service io_;
          boost::asio::deadline_timer timer_;
  
      public:
          SomeClass() : timer_(io_, 1.0/fps*1000.0)
          {
              timer_.async_wait([=]{Display();});
              thread_ = boost::thread([=]{io_.run();})
          }
  
          void Display
          {    
                  double wait = 1.0/fps*1000.0;    
                  while(isRunning_)
                  {
                      timer_.expires_from_now(boost::posix_time::milliseconds(wait_)); // Could this overflow?
  
                      // ... Get Frame. This can block while no frames are being rendered.
  
                      // ... Display Frame.
  
                       timer_.async_wait([=]{Display();});
                  }
          }
      }
  </code></pre>
  
  <p>What am I doing wrong? And if I got this solution working would it be better than the first?</p>