Skip to main content
 首页 » 编程设计

python之运行 Python 程序直到特定时间

2025年05月04日21bonelee

我想在 jupyter notebook 中运行我的程序,这个程序在特定时间停止(例如 18:00)。我用while循环和增量索引写程序,但最好是带时间参数来写。

我每天运行上述程序 7 小时。它必须不停地运行。

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

但我想像下面这样运行我的程序:

    while(not 18:00 clock): 
         execute algorithm 

请您参考如下方法:

您可以创建一个子进程,该子进程将在特定时间终止父进程及其自身:

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 ...