微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

这篇文章主要讲解了“python怎么每天在指定时间段运行程序及关闭程序”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“python怎么每天在指定时间段运行程序及关闭程序”吧!

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

    场景

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

    程序:

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

    python定时程序(每隔一段时间执行指定函数

    import os
    import time
    def print_ts(message):
        print "[%s%s"%(time.strftime("%Y-%m-%d %H:%M:%s", time.localtime()), message)
    def run(interval, command):
        print_ts("-"*100)
        print_ts("Command %s"%command)
        print_ts("Starting every %s seconds."%interval)
        print_ts("-"*100)
        while True:
            try:
                # sleep for the remaining seconds of interval
                time_remaining = interval-time.time()%interval
                print_ts("Sleeping until %s (%s seconds)..."%((time.ctime(time.time()+time_remaining)), time_remaining))
                time.sleep(time_remaining)
                print_ts("Starting command.")
                # execute the command
                status = os.system(command)
                print_ts("-"*100)
                print_ts("Command status = %s."%status)
            except Exception, e:
                print e
    if __name__=="__main__":
        interval = 5
        command = r"ls"
        run(interval, command)

    感谢各位的阅读,以上就是“python怎么每天在指定时间段运行程序及关闭程序”的内容了,经过本文的学习后,相信大家对python怎么每天在指定时间段运行程序及关闭程序这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程之家,小编将为大家推送更多相关知识点的文章,欢迎关注!

    版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

    相关推荐