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

时间:2021-05-28 04:02:54

I am trying to run my python script to run on specific time.

我试图运行我的python脚本在特定时间运行。

For example, I don't want it to run at 12 AM to 3 AM. So it will only run 3AM to 11PM and sleep for 3 hours and run again after 3 AM.

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

I don't want to kill the PID if it runs while it reached 12 AM.. I want it to finish and go to sleep if the time is between 12 AM and 3 AM..

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

for Shell Script:

对于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`

But main question is.. I can't think of a way to do this in python. Also, is there a way to set the sleeping time automatically wake up at 3AM? instead of me setting how long it should sleep?

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

2 个解决方案

#1


0  

Ideally you should be using an existing scheduler, but if you must sleep yourself, the datetime module makes it fairly straightforward:

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

#2


0  

You can use package APScheduler or build-in sched in python.

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

#1


0  

Ideally you should be using an existing scheduler, but if you must sleep yourself, the datetime module makes it fairly straightforward:

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

#2


0  

You can use package APScheduler or build-in sched in python.

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