简体   繁体   English

如何每小时休眠我的python脚本

[英]How to sleep my python script every hour

I want to pause my code every hour mark, ie 11:00pm, 12:00am, 1:00am, etc. 我想每个小时暂停我的代码,例如11:00 pm、12:00am、1:00am等。

How do I go about doing this? 我该怎么做呢?

You have two ways to do this: 您有两种方法可以做到这一点:

cron method cron方法

Add a cron job for your script that gets executed every hour: 为您的脚本添加cron作业,该作业每小时执行一次:

@hourly python /path/to/script

code method 编码方法

Create an infinite loop within your code that runs every hour (have it sleep for 60 minutes). 在每小时运行一次的代码中创建一个无限循环(让其休眠60分钟)。 Or, create an infinite loop within your code that sleeps every minute, have it periodically check what time it is, and if it's on the hour with different delta hour than the current hour, have it run the job. 或者,在您的代码中创建一个无限循环,该循环每分钟休眠一次,让其定期检查现在的时间,以及是否在与当前小时数不同的小时中运行该作业。

import datetime
import time

delta_hour = 0

while:
    now_hour = datetime.datetime.now().hour

    if delta_hour != now_hour:
        # run your code

    delta_hour = now_hour

    time.sleep(60) # 60 seconds

    # add some way to exit the infinite loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM