python 每天在指定时间段运行程序及关闭程序

本文介绍了一个使用Python实现的定时任务管理系统,通过多进程技术,确保程序只在指定的时间段内运行,包括白天的8:30到15:30以及晚上的20:30到次日凌晨2:30。系统会根据当前时间自动启动或关闭子进程,以达到精确的时间控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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()

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值