python如何每天在指定時間段運行程序及關閉程序
更新時間:2023年04月28日 16:36:34 作者:Lee-Oct
這篇文章主要介紹了python如何每天在指定時間段運行程序及關閉程序問題,具有很好的參考價值,希望對大家有所幫助。
python每天在指定時間段運行程序及關閉程序
場景
程序需要在每天某一時間段內(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("關閉子進程")
child_process.terminate()
child_process.join()
child_process = None
print("子進程關閉成功")
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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
閉包在python中的應用之translate和maketrans用法詳解
這篇文章主要介紹了閉包在python中的應用之translate和maketrans用法,是比較實用的技巧,需要的朋友可以參考下2014-08-08
Python 實現(xiàn)LeNet網(wǎng)絡模型的訓練及預測
本文將為大家詳細講解如何使用CIFR10數(shù)據(jù)集訓練模型以及用訓練好的模型做預測。代碼具有一定價值,感興趣的小伙伴可以學習一下2021-11-11

