计算从现在到特定时间点之间的时间

kse8i1jr  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(444)

我试图用python编写一个程序,在每天的特定时间开始执行任务。因为它将永远运行时,电脑是我想让它尽可能轻,我可以。因此,我不想永远检查时间,而是想检查一次时间,计算在正确的时间之前睡眠的时间。

ryhaxcpt

ryhaxcpt1#

无论您选择什么机制来提醒您并运行脚本,都取决于您,但在计算时间方面,您可以使用timedelta。比如说,;

from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(1)

现在你可以想象,你所要做的就是把结果转换成你想要的格式(秒、分钟、小时等)

nvbavucw

nvbavucw2#

你可以

import time

startTime = time.time()
time.sleep(3600) # one hour from current time
if time.time() - startTime > 3600:
 yourTask()

from datetime import datetime, timedelta
import time
currTime = datetime.now()
futureTime = currTime+timedelta(hours = 2) # 2 hours from now, you also can specify days
time.sleep(futureTime-currTime)

# OR Just

time.sleep(timedelta(hours = 2))
yourTask()

这就是python中睡眠和时间函数的一般概念

snvhrwxg

snvhrwxg3#

要每天在同一时间运行相同的函数,可以使用 sched.scheduler 下面的类或不需要该类的解决方案,我在后面展示了该类,它稍微简单一些:
请参阅python事件调度器模块的文档 sched (部分):
课程表。 scheduler (timefunc=time.monotic,delayfunc=time.sleep)
scheduler类定义了调度事件的通用接口。它需要两个函数来实际处理“外部世界”——timefunc应该可以无参数调用,并返回一个数字(“时间”,以任何单位表示)。delayfunc函数应该可以用一个参数调用,与timefunc的输出兼容,并且应该延迟那么多时间单位。在运行每个事件后,还将使用参数0调用delayfunc,以允许其他线程有机会在多线程应用程序中运行。
调度程序。 enterabs (时间、优先级、操作、参数=(),kwargs={})
安排一个新的活动。时间参数应该是与传递给构造函数的timefunc函数的返回值兼容的数字类型。安排在同一时间的事件将按优先级顺序执行。数字越小表示优先级越高。

import datetime
import sched
import time

# number of seconds in:

HOURS_SECONDS = 3600
MINUTES_SECONDS = 60

def my_time_func():
    date_and_time = datetime.datetime.now()
    # convert time component to absolute seconds since midnight:
    return date_and_time.hour * HOURS_SECONDS + date_and_time.minute * MINUTES_SECONDS  + date_and_time.second

def my_sleep_func(t):
    #print('sleeping', t, 'seconds')
    time.sleep(t)

def do_work():
    print('I am working!')

s = sched.scheduler(timefunc=my_time_func, delayfunc=my_sleep_func)

# schedule something to begin every day at (24-hour clock:)

EVENT_HOURS=9
EVENT_MINUTES=35
EVENT_SECONDS=0
first_time = True
while True:
    now = datetime.datetime.now()
    next_event_dt = datetime.datetime(now.year, now.month, now.day, hour=EVENT_HOURS, minute=EVENT_MINUTES, second=EVENT_SECONDS)
    schedule_event = True
    if first_time:
        first_time = False
        # maybe too late for initial schedule day:
        if next_event_dt < now:
            schedule_event = False
    if schedule_event:
        event = s.enterabs(time=EVENT_HOURS * HOURS_SECONDS + EVENT_MINUTES * MINUTES_SECONDS + EVENT_SECONDS, priority=1, action=do_work)
        s.run()
    delta = next_event_dt + datetime.timedelta(days=1) - datetime.datetime.now()
    my_sleep_func(delta.total_seconds())

如果你不想使用 sched.scheduler 类别:

import datetime
import time

# number of seconds in:

HOURS_SECONDS = 3600
MINUTES_SECONDS = 60

def my_sleep_func(t):
    #print('sleeping', t, 'seconds')
    time.sleep(t)

def do_work():
    print('I am working!')

# schedule something to begin every day at (24-hour clock:)

EVENT_HOURS=10
EVENT_MINUTES=30
EVENT_SECONDS=0
first_time = True
while True:
    now = datetime.datetime.now()
    next_event_dt = datetime.datetime(now.year, now.month, now.day, hour=EVENT_HOURS, minute=EVENT_MINUTES, second=EVENT_SECONDS)
    schedule_event = True
    if first_time:
        first_time = False
        # maybe too late for initial schedule day:
        if next_event_dt < now:
            schedule_event = False
    if schedule_event:
        delta = next_event_dt - datetime.datetime.now()
        t = delta.total_seconds()
        if t > 0:
            my_sleep_func(t)
        do_work()
    delta = next_event_dt + datetime.timedelta(days=1) - datetime.datetime.now()
    my_sleep_func(delta.total_seconds())

如果要确保即使程序在事件开始时间之后启动,您的work函数也会在第一天运行,请将循环更改为以下内容(如果使用 sched.scheduler 类别):

while True:
    now = datetime.datetime.now()
    next_event_dt = datetime.datetime(now.year, now.month, now.day, hour=EVENT_HOURS, minute=EVENT_MINUTES, second=EVENT_SECONDS)
    delta = next_event_dt - datetime.datetime.now()
    t = delta.total_seconds()
    if t > 0:
        my_sleep_func(t)
    do_work()
    delta = next_event_dt + datetime.timedelta(days=1) - datetime.datetime.now()
    my_sleep_func(delta.total_seconds())

不用说(但我还是要说), my_sleep_func 只是一个 time.sleep 替换为在取消注解时打印一些诊断信息的功能 print 陈述

相关问题