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


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

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

    场景

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

    程序:

    fromdatetimeimportdatetime,timeimportmultiprocessingfromtimeimportsleep#程序运行时间在白天8:30到15:30晚上20:30到凌晨2:30DAY_START=time(8,30)DAY_END=time(15,30)NIGHT_START=time(20,30)NIGHT_END=time(2,30)defrun_child():while1:print("正在运行子进程")defrun_parent():print("启动父进程")child_process=None#是否存在子进程whileTrue:current_time=datetime.now().time()running=False#子进程是否可运行ifDAY_START<=current_time<=DAY_ENDor(current_time>=NIGHT_START)or(current_time<=NIGHT_END):#判断时候在可运行时间内running=True#在时间段内则开启子进程ifrunningandchild_processisNone:print("启动子进程")child_process=multiprocessing.Process(target=run_child)child_process.start()print("子进程启动成功")#非记录时间则退出子进程ifnotrunningandchild_processisnotNone:print("关闭子进程")child_process.terminate()child_process.join()child_process=Noneprint("子进程关闭成功")sleep(5)if__name__=='__main__':run_parent()

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

    importosimporttimedefprint_ts(message):print"[%s]%s"%(time.strftime("%Y-%m-%d%H:%M:%S",time.localtime()),message)defrun(interval,&nbspmand):print_ts("-"*100)print_ts(&quotmand%s"mand)print_ts("Startingevery%sseconds."%interval)print_ts("-"*100)whileTrue:try:#sleepfortheremainingsecondsofintervaltime_remaining=interval-time.time()%intervalprint_ts("Sleepinguntil%s(%sseconds)..."%((time.ctime(time.time()+time_remaining)),time_remaining))time.sleep(time_remaining)print_ts("Starting&nbspmand.")#executethe&nbspmandstatus=os.systemmand)print_ts("-"*100)print_ts(&quotmandstatus=%s."%status)exceptException,e:printeif__name__=="__main__":interval=5&nbspmand=r"ls"run(interval,&nbspmand)

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


    上一篇:Springboot-admin怎么整合Quartz实现动态管理定时任务

    下一篇:C++怎么实现简单的生产者-消费者队列


    Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
    测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
    温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

    热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器