python如何每天在指定時間段運行程序及關(guān)閉程序
更新時間:2023年04月28日 16:36:34 作者:Lee-Oct
這篇文章主要介紹了python如何每天在指定時間段運行程序及關(guān)閉程序問題,具有很好的參考價值,希望對大家有所幫助。
python每天在指定時間段運行程序及關(guān)閉程序
場景
程序需要在每天某一時間段內(nèi)運行,然后在某一時間段內(nèi)停止該程序。
程序:
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): # 判斷時候在可運行時間內(nèi) running = True # 在時間段內(nèi)則開啟子進程 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("關(guān)閉子進程") child_process.terminate() child_process.join() child_process = None print("子進程關(guān)閉成功") sleep(5) if __name__ == '__main__': run_parent()
python定時程序(每隔一段時間執(zhí)行指定函數(shù))
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)
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python爬蟲中urllib3與urllib的區(qū)別是什么
Urllib3是一個功能強大,條理清晰,用于HTTP客戶端的Python庫。那么Python爬蟲中urllib3與urllib的區(qū)別是什么,本文就詳細的來介紹一下2021-07-07Python 開發(fā)工具通過 agent 代理使用的方法
這篇文章主要介紹了Python 開發(fā)工具通過 agent 代理使用的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09一篇文章弄懂Python中所有數(shù)組數(shù)據(jù)類型
這篇文章主要給大家介紹了關(guān)于Python中所有數(shù)組數(shù)據(jù)類型的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06Anaconda下配置python+opencv+contribx的實例講解
今天小編就為大家分享一篇Anaconda下配置python+opencv+contribx的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08PyTorch的自適應(yīng)池化Adaptive Pooling實例
今天小編就為大家分享一篇PyTorch的自適應(yīng)池化Adaptive Pooling實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01