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

时间:2015-03-16 15:16:06

标签: python linux bash shell unix

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

例如,我不希望它在凌晨12点到凌晨3点运行。 所以它只会在凌晨3点到晚上11点运行,然后睡3个小时,然后在凌晨3点再次运行。

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

for Shell Script:

 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点自动唤醒?而不是我设定它应该睡多久?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

理想情况下,您应该使用现有的调度程序,但如果您必须自己休眠,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 ...
相关问题