【问题标题】:In python, how can I begin a program at a given system time?在 python 中,如何在给定的系统时间启动程序?
【发布时间】:2013-09-14 19:50:34
【问题描述】:

在 python 中,我一直使用 sleep 每小时、每分钟或每天执行一段循环代码。问题是脚本需要大约 1-3 秒才能运行。如何确保脚本在下一分钟到来时开始,例如我启动脚本并且当前分钟还剩 20 秒。

使用时间我得到这些结果,注意我每秒钟都失去精度:

Waiting for next half min.
2013-09-14 15:46:53.850068
307
Waiting for next half min.
2013-09-14 15:47:24.158642
307
Waiting for next half min.
2013-09-14 15:47:54.717070
302
Waiting for next half min.
2013-09-14 15:48:25.296409
325
Waiting for next half min.
2013-09-14 15:48:55.506098

【问题讨论】:

  • 展示你的 Python 代码,或者购买速度更快的硬件。
  • 当你完成你当前的任务后,计算出你下次想跑多长时间,然后再睡那么久。
  • 同意@tcaswell,似乎是最直接的方法。
  • 如果您每分钟定期运行脚本,则 Linux 上的 cron 作业或 Windows 上的计划任务
  • @pxl 我认为这也是正确的方法

标签: python loops python-2.7 time wait


【解决方案1】:

我认为你的时间不精确是由于不可预测的 python 解释器启动时间。

如果您需要确保您的实际代码在准确的时间开始执行,您可以执行以下操作:

  • 让你的脚本比你需要的早一点运行
  • 在脚本中:

    import time
    import datetime
    
    schedule_time = ... # parse sys.argv or whatevs
    
    # this will wait exactly as much time as it is left before the schedule
    time.sleep((schedule_time - datetime.datetime.now()).total_seconds())
    # ... your code
    

【讨论】:

  • 不,我的问题确实与函数耗时有关,因为它正在收集数据,这需要 0 到 5 秒。
【解决方案2】:

您需要在每次代码运行后计算出适当的睡眠时间。下面的代码会做到这一点,并且还会尝试在工作任务花费的时间超过延迟间隔的情况下赶上。

import time

# Get the start time, also the time of the next (first) iteration
lTimeNext = time.time()

# Set up the delay time
lDelay = 30

# Loop, doing work
while True:

  # Do Work
  print "Working!"

  # Work out when to do the next work item
  lTimeNext += lDelay

  # Sleep until the next work is required
  lSleepTime = lTimeNext - time.time()
  if lSleepTime > 0:
    time.sleep(lSleepTime)

【讨论】:

    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2013-02-26
    • 2013-12-27
    • 1970-01-01
    • 2012-07-16
    • 2017-08-14
    相关资源
    最近更新 更多