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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With