標籤:odi pen def lines request else trace rgs list
定時任務的原理
伺服器執行一個python指令碼
這個指令碼,迴圈執行配置的定時任務地址
Python請求地址, 該地址應該返回, 下次再來執行的秒數. 也就是任務的頻率
比如任務希望每3秒執行一次, 那麼任務結束後,應該返回一個3的數字
python指令碼拿到任務返回的數字, 算出下次執行任務的時間. 當時間條件滿足是, python指令碼會繼續訪問該任務
不同的任務, 直接修改 init裡面的配置就可以了
python指令碼如下:
#!/usr/bin/env python3# -*- coding: utf-8 -*-import threadingimport timeimport urllib.requestimport os,statclass MyThread(object): ‘‘‘ 多線程 ‘‘‘ def __init__(self, func_list=None,timeout=5): self.threads = [] self.rs = {} self.timeout = timeout self.func_list = func_list self.start() #封裝的線程函數 def trace_func(self, func, name , *args, **kwargs): ret = func(*args, **kwargs) self.rs[name] = ret #執行多線程 def start(self): for v in self.func_list: if v["args"]: lists = [] lists.append(v["func"]) lists.append(v["name"]) for arg in v["args"]: lists.append(arg) tuples = tuple(lists) t = threading.Thread(target=self.trace_func, args=tuples) else: t = threading.Thread(target=self.trace_func, args=(v["func"],v["name"],)) self.threads.append(t) for t in self.threads: t.start() for t in self.threads: t.join() #t.join(self.timeout)‘‘‘執行任務‘‘‘def task(url, last_time): #目前時間, 最後執行時間 cur_time = int(time.time()) last_time = int(last_time) if last_time==0: last_time = cur_time #滿足條件就執行任務 if cur_time>=last_time: print("請求:%s"%(url)) try: req = urllib.request.urlopen(url) content = req.read() content = str(content, ‘utf-8‘) content = content.strip() if content.isdigit(): last_time += int(content) else: last_time += 1000 except: print(‘發生了異常, 重設檔案‘) init() return last_time‘‘‘多線程調用定時任務‘‘‘def main(): #讀取檔案 with open("config.txt",‘r‘) as f: lines = f.readlines() f.close() #多線程執行 func_list = [] for v in lines: v = v.split(‘|‘) v[1] = int(v[1]) func_list.append({"func":task,"args":(v[0], v[1]), "name":v[0]}) mt = MyThread(func_list) d = mt.rs #重新寫入檔案 content = ‘‘ for k in d: content += "%s|%s\n" % (k,str(d[k])) with open("config.txt",‘w‘) as f: f.write(content) f.close()‘‘‘初始化要執行的定時任務‘‘‘def init(): urls = [ ‘http://admin.yqxv1.local/task/withdraw‘, ‘http://baidu.com‘ ] content = ‘‘ for v in urls: content += "%s|%s\n" % (v,0) with open("config.txt",‘w+‘) as f: f.write(content) f.close() os.chmod("config.txt",stat.S_IRWXU)init()while True: main()
python版 定時任務機制