Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleeping until the start of the next minute

Tags:

time

haskell

I'm trying to write some code to sleep until the start of the next minute in the local timezone, but am having great difficulty doing so. The time library has always been one of my weak points, so I'm assuming there's some easy way to do this.

I thought of just computing a new TimeOfDay, but that wouldn't handle 23:59 to 00:00, and would presumably do very confusing things with daylight savings time switch-overs.

Handling leap seconds would be a nice bonus, too.

Using Control.Concurrent.threadDelay to do the sleeping seems like the simplest method to me, so an alternate question would be: How can I get the number of microseconds until the start of the next minute? DiffTime and NominalDiffTime would be perfectly acceptable ways to achieve this.

like image 891
ehird Avatar asked Dec 20 '11 12:12

ehird


1 Answers

I worry this may not be what you want given your later comments. I think this would tolerate leap years, timezone changes, and day changes, but not leap seconds.

import Control.Concurrent (threadDelay)
import Data.Time.Clock

sleepToNextMinute :: IO ()
sleepToNextMinute = do t <- getCurrentTime
                       let secs = round (realToFrac $ utctDayTime t) `rem` 60
                       threadDelay $ 1000000 * (60 - secs)

main = do putStrLn "Starting..."
          sleepToNextMinute
          putStrLn "Minute 1"
          sleepToNextMinute
          putStrLn "Minute 2"
like image 114
Anthony Avatar answered Oct 24 '22 10:10

Anthony