title: Are there any well-behaved POSIX interval timers?
body: <p>Inspired by the last leap second, I've been exploring timing (specifically, interval timers) using POSIX calls.</p>
  
  <p>POSIX provides several ways to set up timers, but they're all problematic:</p>
  
  <ul>
  <li><code>sleep</code> and <code>nanosleep</code>—these are annoying to restart after they're interrupted by a signal, and they introduce clock skew. You can avoid some, but not all, of this skew with some extra work, but these functions use the realtime clock, so this isn't without pitfalls.</li>
  <li><code>setitimer</code> or the more modern <code>timer_settime</code>—these are designed to be interval timers, but they're per-process, which is a problem if you need multiple active timers. They also can't be used synchronously, but that's less of a big deal.</li>
  <li><code>clock_gettime</code> and <code>clock_nanosleep</code> seem like the right answer when used with <code>CLOCK_MONOTONIC</code>. <code>clock_nanosleep</code> supports absolute timeouts, so you can just sleep, increment the timeout, and repeat. It's easy to restart after an interruption that way, too. Unfortunately, these functions might as well be Linux-specific: there's no support for them on Mac OS X or FreeBSD.</li>
  <li><code>pthread_cond_timedwait</code> is available on the Mac and can work with <code>gettimeofday</code> as a kludgy workaround, but on the Mac it can only work with the realtime clock, so it's subject to misbehavior when the system clock is set or a leap second happens.</li>
  </ul>
  
  <p>Is there an API I'm missing? Is there a reasonably portable way to create well-behaved interval timers on UNIX-like systems, or does this sum up the state of things today?</p>
  
  <p>By well-behaved and reasonably portable, I mean:</p>
  
  <ul>
  <li>Not prone to clock skew (minus, of course, the system clock's own skew)</li>
  <li>Resilient to the system clock being set or a leap second occurring</li>
  <li>Able to support multiple timers in the same process</li>
  <li>Available on at least Linux, Mac OS X, and FreeBSD</li>
  </ul>
  
  <p><strong>A note on leap seconds</strong> (in response to <a href="https://stackoverflow.com/a/11343516/195298">R..'s answer</a>):</p>
  
  <p>POSIX days are exactly 86,400 seconds long, but real-world days can rarely be longer or shorter. How the system resolves this discrepancy is implementation-defined, but it's common for the leap second to share the same UNIX timestamp as the previous second. See also: <a href="http://derickrethans.nl/leap-seconds-and-what-to-do-with-them.html" rel="noreferrer">Leap Seconds and What To Do With Them</a>.</p>
  
  <p>The Linux kernel leap second bug was a result of failing to do housekeeping after setting the clock back a second: <a href="https://lkml.org/lkml/2012/7/1/203" rel="noreferrer">https://lkml.org/lkml/2012/7/1/203</a>. Even without that bug, the clock <em>would</em> have jumped backwards one second.</p>