Run Python Program Until Specific Time

核能气质少年 提交于 2021-02-19 08:35:09

问题


I want to run my program in jupyter notebook and this program stops at specific time(for example 18:00). I wrote program by while loop and incremental index, but it's better to write it with time parameter.

I run mentioned program for 7 hours each day. It must run nonstop.

    while(i<500000):
         execute algorithm
         i+=1

But I'd like to run my program like bellow:

    while(not 18:00 clock):
         execute algorithm

回答1:


import datetime

while datetime.datetime.now().hour < 18:
    do stuff...

or

if datetime.datetime.now().hour >= 18:
    return



回答2:


You can create a child process that will terminate parent process and itself at certain time:

import multiprocessing as mp
import time
import datetime
import sys
import signal
import os

def process(hr, minute):
    while True:
        d = datetime.datetime.now()
        if d.hour == hr and d.minute == minute:
            os.kill(os.getppid(), signal.SIGTERM)
            sys.exit()
        else:
            time.sleep(25)


p = mp.Process(target=process, args=(18, 0))
p.start()

# your program here ...



回答3:


Use:

import datetime
#create the alarm clock.
alarm = datetime.time(15, 8, 24) #Hour, minute and second you want.

On while:

while alarm < datetime.datetime.now().time():
    do something

You could set a specific date too, setting like this:

datetime.datetime(2019, 3, 21, 22, 0, 0)  #Year, month, day, hour, minute and second you want.

For more info, check the documentation of datetime.




回答4:


You could create a function that takes hour and minutes as parameters and to perform a check inside the while loop:

import datetime

def proc(h, m):
    while True:
        currentHour = datetime.datetime.now().hour
        currentMinute = datetime.datetime.now().minute
        if currentHour == h and currentMinute == m:
            break
        # Do stuff...

# Function call.
proc(18,0)



回答5:


import datetime

https://docs.python.org/3/library/datetime.html

You can then use the various functions (time or timedelta) to set a time.

timeNow = datetime.datetime() print timeNow




回答6:


You could set this up as a cron job and start the job at time x and stop at time x.




回答7:


Let us assume you want you code to run 10 pm(22:oo) hour every day. If you are using Linux, you can do something like this to run job as root user

sudo crontab -e 
0 22 * * *  /path/to/directory/python my_code.py

your python file my_code.py could be something like that

# python code to search pattern in a string using regex
import re

str1 = 'this is {new} string with [special] words.'

r = re.search(r'\{(.*?)\}', str1)
if r:
    found =r.group()
else:
    "No match found"

print found


来源:https://stackoverflow.com/questions/55287184/run-python-program-until-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!