python - 在Python中让线程休眠直到特定时间

标签 python multithreading datetime sleep timedelta

我编写了一个脚本,该脚本创建的线程在发送电子邮件之前会自行休眠直到一天中的某个时间。有些在脚本运行当天下午 4 点运行,有些则在第二天早上 7 点运行。

我的问题是,应该在下午 4 点运行的线程通常要到下午 5 点或 6 点才会运行,而早上 7 点的线程总是准时运行。该脚本通常在上午 10 点至下午 1 点之间启动。我正在使用Python 2.6.6

代码简单来说如下:

from datetime import datetime, timedelta
import threading

def main():
  today = datetime.now()
  today_at_4pm = today.replace(hour=16, minute=0, second=0)

  tomorrow = today + timedelta(days=1)
  tomorrow_at_7am = tomorrow.replace(hour=7, minute=0, second=0)

  message = "some message"
  threading.Thread(target=dispatchEmail, args=(message, today_at_4pm)).start()
  threading.Thread(target=dispatchEmail, args=(message, tomorrow_at_7am)).start()


def dispatchEmail(message, time_to_send):
  now = datetime.now()

  if now < time_to_send:
    time_diff = time_to_send - now
    diff_in_seconds = (time_diff.days * 86400) + time_diff.seconds
    sleep(diff_in_seconds)

  sendEmail(message)

def sendEmail(message):
  print message

if __name__ == '__main__': main()

我无法确定问题所在,因为它在发送时不一致,并且在短时间内运行它没有任何问题。 diff_in_seconds 计算似乎也是准确的。

我认为错误在于 sleep 部分或我对线程如何工作的误解。非常感谢任何帮助。

对于那些认为我应该分离脚本并使用 crontasks 的人来说——我宁愿不这样做,因为消息的实际内容是如何从文件中读取/跟踪的。

更新

我通过 python sched 文档找到了 threading.Timer 方法。这允许我在一段时间后运行该函数。我将 sleep 时间计算移出了dispatchEmail,这使我能够摆脱它:

def timeDifference(now, time_to_send):
  if now < time_to_send:
    time_difference = time_to_send - now
    return (time_difference.days * 86400) + time_difference.seconds
  else:
    return 0

time_until_4pm = timeDifference(datetime.now(), today_at_4pm)
time_until_7am = timeDifference(datetime.now(), tomorrow_at_7am)

threading.Timer(time_until_4pm, sendEmail, (message))
threading.Timer(time_until_7am, sendEmail, (message))

这方面有什么我需要注意的细微差别吗?

最佳答案

不要使用线程休眠。这绝对是错误的解决问题的方法。如果您不想使用 crons(我假设您的意思是字面的 linux cron 作业),请使用类似 https://docs.python.org/2/library/sched.html 的内容。

关于python - 在Python中让线程休眠直到特定时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31417661/

相关文章:

javascript - 解析 date-fns 返回前一天的值

python - 两个日期时间之间的 15 分钟间隔数

ruby-on-rails - ActiveRecord 为 Time of 26 :12 返回 "argument out of range"

python - Python 中的分段 TCP 消息

python - numpy 数组 : IndexError: too many indices for array

python - 为什么不同的格式方法在 Python 中表现不同?

python - 如何在 pandas groupby 中聚合多列

python - 如何限制创建的Thread对象的数量?

c - 在不同机器上具有不同输出的并行代码

multithreading - 调用performSelectorInBackground : from background thread