在Python中,如何让线程在特定时间内进入休眠状态?

时间:2022-12-07 20:48:40

I know that I can cause a thread to sleep for a specific amount of time with:

我知道我可以让线程在特定的时间内睡眠:

time.sleep(NUM)

How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?

如何让线程睡到凌晨2点?我必须做数学来确定直到凌晨2点的秒数吗?还是有一些库功能?

( Yes, I know about cron and equivalent systems in Windows, but I want to sleep my thread in python proper and not rely on external stimulus or process signals.)

(是的,我知道Windows中的cron和等效系统,但我想在python中正确地睡觉我的线程而不依赖于外部激励或处理信号。)

6 个解决方案

#1


32  

Here's a half-ass solution that doesn't account for clock jitter or adjustment of the clock. See comments for ways to get rid of that.

这是一个半分辨率解决方案,不考虑时钟抖动或时钟调整。请参阅评论以了解如何摆脱它。

import time
import datetime

# if for some reason this script is still running
# after a year, we'll stop after 365 days
for i in xrange(0,365):
    # sleep until 2AM
    t = datetime.datetime.today()
    future = datetime.datetime(t.year,t.month,t.day,2,0)
    if t.hour >= 2:
        future += datetime.timedelta(days=1)
    time.sleep((future-t).seconds)

    # do 2AM stuff

#2


15  

import pause
from datetime import datetime

pause.until(datetime(2015, 8, 12, 2))

#3


3  

One possible approach is to sleep for an hour. Every hour, check if the time is in the middle of the night. If so, proceed with your operation. If not, sleep for another hour and continue.

一种可能的方法是睡一个小时。每小时一次,检查时间是否在半夜。如果是,请继续操作。如果没有,请再睡一小时并继续。

If the user were to change their clock in the middle of the day, this approach would reflect that change. While it requires slightly more resources, it should be negligible.

如果用户在一天中间改变他们的时钟,这种方法将反映出这种变化。虽然它需要稍多的资源,但它应该可以忽略不计。

#4


3  

I tried the "pause" pacakage. It does not work for Python 3.x. From the pause package I extracted the code required to wait until a specific datetime and made the following def.

我尝试了“暂停”的pacakage。它不适用于Python 3.x.从暂停包中我提取了等待特定日期时间所需的代码并进行了以下def。

def wait_until(execute_it_now):
    while True:
        diff = (execute_it_now - datetime.now()).total_seconds()
        if diff <= 0:
            return
        elif diff <= 0.1:
            time.sleep(0.001)
        elif diff <= 0.5:
            time.sleep(0.01)
        elif diff <= 1.5:
            time.sleep(0.1)
        else:
            time.sleep(1)

#5


1  

Slightly beside the point of the original question:

稍微偏离原始问题的要点:

Even if you don't want to muck around with crontabs, if you can schedule python scripts to those hosts, you might be interested to schedule anacron tasks? anacron's major differentiator to cron is that it does not rely the computer to run continuously. Depending on system configuration you may need admin rights even for such user-scheduled tasks.

即使您不想使用crontabs,如果您可以将python脚本安排到这些主机,您可能有兴趣安排anacron任务? anacron与cron的主要区别在于它不依赖于计算机连续运行。根据系统配置,即使对于此类用户计划任务,您也可能需要管理员权限。

A similar, more modern tool is upstart provided by the Ubuntu folks: http://upstart.ubuntu.com/ This does not yet even have the required features. But scheduling jobs and replacing anacron is a planned feature. It has quite some traction due to its usage as Ubuntu default initd replacement. (I am not affiliated with the project)

一个类似的,更现代的工具是由Ubuntu人员提供的新贵:http://upstart.ubuntu.com/这甚至还没有所需的功能。但安排工作和更换anacron是一项计划的功能。由于其用作Ubuntu默认的initd替换,它具有相当大的吸引力。 (我不隶属于该项目)

Of course, with the already provided answer, you can code the same functionality into your python script and it might suit you better in your case.

当然,通过已经提供的答案,您可以在python脚本中编写相同的功能,在您的情况下它可能更适合您。

Still, for others, anacron or similar existing systems might be a better solution. anacron is preinstalled on many current linux distributions (there are portability issues for windows users).

但是,对于其他人来说,anacron或类似的现有系统可能是更好的解决方案。 anacron预装在许多当前的Linux发行版上(Windows用户存在可移植性问题)。

Wikipedia provides a pointer page: https://en.wikipedia.org/wiki/Anacron

*提供了一个指针页面:https://en.wikipedia.org/wiki/Anacron

If you do go for a python version I'd look at the asynchronous aspect, and ensure the script works even if the time is changed (daylight savings, etc) as others have commented already. Instead of waiting til a pre-calculated future, I'd always at maximum wait one hour, then re-check the time. The compute cycles invested should be negligible even on mobile, embedded systems.

如果您选择python版本,我会查看异步方面,并确保即使时间已经改变(夏令时等),脚本仍然有效,因为其他人已经评论过了。而不是等待直到预先计算的未来,我总是等待一个小时,然后重新检查时间。即使在移动嵌入式系统上,投入的计算周期也应该可以忽略不计。

#6


-2  

from datetime import datetime
import time, operator
time.sleep([i[0]*3600 + i[1]*60 for i in [[H, M]]][0] - [i[0]*3600 + i[1]*60 for i in [map(int, datetime.now().strftime("%H:%M").split(':'))]][0])

#1


32  

Here's a half-ass solution that doesn't account for clock jitter or adjustment of the clock. See comments for ways to get rid of that.

这是一个半分辨率解决方案,不考虑时钟抖动或时钟调整。请参阅评论以了解如何摆脱它。

import time
import datetime

# if for some reason this script is still running
# after a year, we'll stop after 365 days
for i in xrange(0,365):
    # sleep until 2AM
    t = datetime.datetime.today()
    future = datetime.datetime(t.year,t.month,t.day,2,0)
    if t.hour >= 2:
        future += datetime.timedelta(days=1)
    time.sleep((future-t).seconds)

    # do 2AM stuff

#2


15  

import pause
from datetime import datetime

pause.until(datetime(2015, 8, 12, 2))

#3


3  

One possible approach is to sleep for an hour. Every hour, check if the time is in the middle of the night. If so, proceed with your operation. If not, sleep for another hour and continue.

一种可能的方法是睡一个小时。每小时一次,检查时间是否在半夜。如果是,请继续操作。如果没有,请再睡一小时并继续。

If the user were to change their clock in the middle of the day, this approach would reflect that change. While it requires slightly more resources, it should be negligible.

如果用户在一天中间改变他们的时钟,这种方法将反映出这种变化。虽然它需要稍多的资源,但它应该可以忽略不计。

#4


3  

I tried the "pause" pacakage. It does not work for Python 3.x. From the pause package I extracted the code required to wait until a specific datetime and made the following def.

我尝试了“暂停”的pacakage。它不适用于Python 3.x.从暂停包中我提取了等待特定日期时间所需的代码并进行了以下def。

def wait_until(execute_it_now):
    while True:
        diff = (execute_it_now - datetime.now()).total_seconds()
        if diff <= 0:
            return
        elif diff <= 0.1:
            time.sleep(0.001)
        elif diff <= 0.5:
            time.sleep(0.01)
        elif diff <= 1.5:
            time.sleep(0.1)
        else:
            time.sleep(1)

#5


1  

Slightly beside the point of the original question:

稍微偏离原始问题的要点:

Even if you don't want to muck around with crontabs, if you can schedule python scripts to those hosts, you might be interested to schedule anacron tasks? anacron's major differentiator to cron is that it does not rely the computer to run continuously. Depending on system configuration you may need admin rights even for such user-scheduled tasks.

即使您不想使用crontabs,如果您可以将python脚本安排到这些主机,您可能有兴趣安排anacron任务? anacron与cron的主要区别在于它不依赖于计算机连续运行。根据系统配置,即使对于此类用户计划任务,您也可能需要管理员权限。

A similar, more modern tool is upstart provided by the Ubuntu folks: http://upstart.ubuntu.com/ This does not yet even have the required features. But scheduling jobs and replacing anacron is a planned feature. It has quite some traction due to its usage as Ubuntu default initd replacement. (I am not affiliated with the project)

一个类似的,更现代的工具是由Ubuntu人员提供的新贵:http://upstart.ubuntu.com/这甚至还没有所需的功能。但安排工作和更换anacron是一项计划的功能。由于其用作Ubuntu默认的initd替换,它具有相当大的吸引力。 (我不隶属于该项目)

Of course, with the already provided answer, you can code the same functionality into your python script and it might suit you better in your case.

当然,通过已经提供的答案,您可以在python脚本中编写相同的功能,在您的情况下它可能更适合您。

Still, for others, anacron or similar existing systems might be a better solution. anacron is preinstalled on many current linux distributions (there are portability issues for windows users).

但是,对于其他人来说,anacron或类似的现有系统可能是更好的解决方案。 anacron预装在许多当前的Linux发行版上(Windows用户存在可移植性问题)。

Wikipedia provides a pointer page: https://en.wikipedia.org/wiki/Anacron

*提供了一个指针页面:https://en.wikipedia.org/wiki/Anacron

If you do go for a python version I'd look at the asynchronous aspect, and ensure the script works even if the time is changed (daylight savings, etc) as others have commented already. Instead of waiting til a pre-calculated future, I'd always at maximum wait one hour, then re-check the time. The compute cycles invested should be negligible even on mobile, embedded systems.

如果您选择python版本,我会查看异步方面,并确保即使时间已经改变(夏令时等),脚本仍然有效,因为其他人已经评论过了。而不是等待直到预先计算的未来,我总是等待一个小时,然后重新检查时间。即使在移动嵌入式系统上,投入的计算周期也应该可以忽略不计。

#6


-2  

from datetime import datetime
import time, operator
time.sleep([i[0]*3600 + i[1]*60 for i in [[H, M]]][0] - [i[0]*3600 + i[1]*60 for i in [map(int, datetime.now().strftime("%H:%M").split(':'))]][0])