如何在特定时间打印文件

3

是否有可能让Python 2.7在一天的特定时间打印某些内容?例如,如果我在15:06运行程序并编写代码,在15:07打印“现在进行任务”,它会打印出来。因此,无论您何时运行程序,一旦到达15:07,它都会打印“现在进行任务”。此外,是否可以使其每周在此时间打印?


是的,Python 可以做到。 - Stephen Rauch
谢谢@StephenRauch,但我该如何编写代码? - Ryan
我建议调查datetime模块。https://docs.python.org/3/library/datetime.html - Stephen Rauch
1
@cricket_007,用户需要这个功能可能有很好的理由,我们不知道也不能假设它只是用于任务调度。 - the_constant
@Ryan 不用谢。另外,什么时候我们决定“现在是15:07之前”,这意味着如果我们在今天凌晨1点运行它,那么这是在15:07之前还是之后?截止时间是午夜吗?你的问题中的每一周是指每周的某一天吗? - the_constant
显示剩余5条评论
3个回答

6

如果您有能力,我建议安装库“schedule”。

使用pip install schedule

如果使用schedule,您的代码将如下所示:

import schedule
import time

def task():
    print("Do task now")

schedule.every().day.at("15:07").do(task)

while True:
    schedule.run_pending()
    time.sleep(1)

如果 1 秒的时间间隔太长,您可以根据需要调整 time.sleep(1) 的时间。这是schedule库页面


1
虽然Python不是最理想的调度工具,但市面上有更好的工具。如果希望在Python中完成此操作,可以按照以下方式实现:

scheduled_time的11AM打印:

import datetime as dt
scheduled_time = dt.time(11,00,00,0)
while 1==1:
    if (scheduled_time < dt.datetime.now().time() and 
       scheduled_time > (dt.datetime.now()- dt.timedelta(seconds=59)).time() ):
        print "Now is the time to print"
        break

有两个 if 条件,意图在一分钟内打印; 可以选择更短的持续时间。但是,在 print 后立即使用 break 确保只执行一次 print

您需要推广此代码,以便跨越几天运行。

参考:datetime 文档


1
如果您没有使用,那么通用解决方案是找到需要事件发生的剩余时间,让程序休眠该持续时间,然后继续执行。

棘手的部分是使程序找到给定时间的下一个出现。有一些模块可以做到这一点,但对于仅为固定时间的情况,您也可以使用普通代码来完成。

import time

target_time = '15:07:00'
current_epoch = time.time()

# get string of full time and split it
time_parts = time.ctime().split(' ')
# replace the time component to your target
time_parts[3] = target_time
# convert to epoch
future_time = time.mktime(time.strptime(' '.join(time_parts)))

# if not in the future, add a day to make it tomorrow
diff = future_time - current_epoch
if diff < 0:
    diff += 86400

time.sleep(diff)
print 'Done waiting, lets get to work'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接