繁体   English   中英

如何设置在Python脚本中运行的时间

[英]How can I set up the time to run in Python Script

我正在尝试运行我的python脚本以在特定时间运行。

例如,我不希望它在12 AM到3 AM运行。 因此,它将仅在凌晨3点至晚上11点运行并睡眠3小时,然后在凌晨3点后再次运行。

如果PID在达到12 AM时运行,我不想杀死它。如果时间在12 AM至3 AM之间,我希望它完成并进入睡眠状态。

对于Shell脚本:

 while true
 do
       curr_time=`date +"%H%M%S"`
       if [ $curr_time -ge 235000 -a $curr_time -le 030000 ]
       then
            sleep 12000 
            #Going to check time before 12AM so that it can stop before 12
            #Sleep for little more than 3hours since it might stop before 3AM
       else
            break;
       fi
 done`

但是主要的问题是..我想不出一种在python中做到这一点的方法。 另外,有没有办法设置睡眠时间在凌晨3点自动唤醒? 而不是我设定应该睡多久?

您可以使用包APScheduler或python中的内置sched

理想情况下,您应该使用现有的调度程序,但是如果您必须睡觉,则datetime模块使其非常简单:

import datetime
while 1:
    now = datetime.datetime.now()
    if now.hour < 3:
        at_3 = datetime.datetime.combine(datetime.date.today(),
                                         datetime.time(3))
        to_sleep = (at_3 - now).seconds
        time.sleep(to_sleep)

    # do the work ...

暂无
暂无

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

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