睡觉,直到下一分钟的开始 [英] Sleeping until the start of the next minute

查看:140
本文介绍了睡觉,直到下一分钟的开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些代码,直到当地时区的下一分钟开始,但这样做很困难。 时间库一直是我的弱点之一,所以我假设有一些简单的方法来做到这一点。



我以为只是计算一个新的 TimeOfDay ,但不能处理23:59到00:00,并且大概会在夏时制切换时做很混乱的事情。

使用

使用 Control.Concurrent.threadDelay 来做睡觉似乎对我来说是最简单的方法,所以另一个问题是:我怎样才能得到微秒直到下一分钟的开始? DiffTime NominalDiffTime 是完全可以接受的方式。

解决方案

我担心这可能不是您想要的,因为您以后的评论。我认为这可以容忍闰年,时区更改和日期更改,但不能闰秒。

  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 putStrLnStarting ...
sleepToNextMinute
putStrLn分钟1
sleepToNextMinute
putStrLn分钟2


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"

这篇关于睡觉,直到下一分钟的开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆