posts - 225, comments - 62, trackbacks - 0, articles - 0
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理
# -*- coding: utf-8 -*-

import multiprocessing
import time
import datetime
import signal
import sys

def run_child_process(child_process_running):
    """子进程运行函数"""
    print("Init", flush=True)
    while child_process_running.value:
        print("Run", flush=True)
        time.sleep(1)
    print("Exit", flush=True)


def is_between_time(t, b, e):
    if b <= e:
        return b <= t < e
    else:
        return b <= t or t < e

running = True
def on_SIGINT(signum, frame):
    global running
    running = False

def run_parent_process():
    """父进程运行函数"""
    day_start = datetime.time(7, 0)  # 启动时间
    day_end = datetime.time(17, 0)  # 停止时间

    child_process = None  # 子进程句柄
    child_process_running = multiprocessing.Value('i')
    child_process_running.value = False
    last_ts = time.time()
    retry_cnt = 0
    while running:
        dt = datetime.datetime.now()
        current_time = dt.time()
        # today = dt.date()

        if is_between_time(current_time, day_start, day_end):
            child_process_running.value = True
        else:
            child_process_running.value = False

        if child_process_running.value:  # 交易时间则需要启动子进程
            if child_process is None:
                retry_cnt = 0
                child_process = multiprocessing.Process(target=run_child_process, args=(child_process_running,))
                child_process.start()
            elif not child_process.is_alive(): # 异常崩溃的情况
                retry_cnt += 1
                if retry_cnt < 3:
                    child_process = multiprocessing.Process(target=run_child_process, args=(child_process_running,))
                    child_process.start()
                else:
                    print(f"子进程异常崩溃{retry_cnt}次,结束父进程")
                    sys.exit(1)

        else:  # 非交易时间则退出子进程
            if child_process is not None:
                child_process.join(10)
                if child_process.is_alive():
                    child_process.terminate()
                child_process = None

        ts = time.time()
        if ts - last_ts >= 100:
            print('[{}]'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), 'Parent Process Alive')
            last_ts = ts
        time.sleep(1)

    child_process_running.value = False
    if child_process is not None:
        child_process.join(10)
        if child_process.is_alive():
            child_process.terminate()
        child_process = None

signal.signal(signal.SIGINT, on_SIGINT)

if __name__ == '__main__':
    run_parent_process()
只有注册用户登录后才能发表评论。