场景:程序需要在每天某一时间段内运行,然后在某一时间段内停止该程序。

来源于https://blog.csdn.net/weixin_35737303/article/details/99561792

from datetime import datetime, time
import multiprocessing
from time import sleep

# 程序运行时间在白天8:30 到 15:30 晚上20:30 到 凌晨 2:30
DAY_START = time(8, 30)
DAY_END = time(15, 30)

NIGHT_START = time(20, 30)
NIGHT_END = time(2, 30)


def run_child():
while 1:
print("正在运行子进程")


def run_parent():
print("启动父进程")

child_process = None # 是否存在子进程

while True:
current_time = datetime.now().time()
running = False # 子进程是否可运行

if DAY_START <= current_time <= DAY_END or (current_time >= NIGHT_START) or (current_time <= NIGHT_END):
# 判断时候在可运行时间内
running = True

# 在时间段内则开启子进程
if running and child_process is None:
print("启动子进程")
child_process = multiprocessing.Process(target=run_child)
child_process.start()
print("子进程启动成功")

# 非记录时间则退出子进程
if not running and child_process is not None:
print("关闭子进程")
child_process.terminate()
child_process.join()
child_process = None
print("子进程关闭成功")

sleep(5)


if __name__ == '__main__':
run_parent()
————————————————
版权声明:本文为CSDN博主「AzureL_」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_35737303/java/article/details/99561792

猜你喜欢

转载自www.cnblogs.com/sqzqllaozhuo/p/12639647.html
今日推荐