2015-09-07 20 views
-1

我需要編寫一個運行python腳本的python守護進程,並通過TCP將它們的輸出發送到服務器。每個腳本應該每N秒運行一次(例如,第一個 - 每10秒鐘,第二個 - 每3秒鐘和第三個 - 每200秒鐘等)。 運行時,守護程序會查找包含腳本路徑及其時間延遲的配置文件(我可以在上面以秒爲單位呼叫?)。然後這個守護進程在適當的時候調用腳本。Python定時器引擎

我在問的問題是如何使這個簡單的計時器引擎?有沒有現成的解決方案?

P.S.我有一個想法。這樣的想法是這樣的事情:

  1. 初始化啓動時間(啓動守護進程的時間) - START_TIME
  2. 使腳本的時間延遲的陣列 - time_delays []
  3. 每一秒做的事:

    now_time = int(datetime.datetime.now().timestamp()) 
    
    for x in time_delays: 
    
        diff = start_time - now_time    
    
        if diff % x == 0: 
    
         # Good! Let's run script file 
    
+0

我建議你嘗試一下你想出來的想法,如果它無法按預期工作,或者遇到任何與編程有關的問題 –

回答

0

只需使用一個調度程序,在這裏看到的API https://apscheduler.readthedocs.org/en/latest/#下面是一個簡單的例子:

from apscheduler.schedulers.blocking import BlockingScheduler 
import logging 
logging.basicConfig() 

def t1(): 
    #run file1 with a PUB\SUB routine 

def t2(): 
    #run file2 with a PUB\SUB routine 

def t3(): 
    #run file3 with a PUB\SUB routine 

if __name__ == '__main__': 
    scheduler = BlockingScheduler() 
    sched.add_interval_job(t1, minutes=1, start_date='2013-08-06 00:09:12') 
    scheduler.add_job(t2, 'cron', day_of_week='mon-fri', hour=1, minute=2) 
    scheduler.add_job(t3, 'cron', day_of_week='mon-fri', hour=1, second=10) 
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) 
    try: 
     scheduler.start() 
    except (KeyboardInterrupt, SystemExit): 
     pass 
0

你簡單的問題掩蓋了最後會是什麼更復雜的東西。
你將需要一個配置函數,一個定時器函數,線程和pubsub(或其他一些機制)來傳達腳本已經完成,並且最終需要套接字或ftp來與服務器進行通信,其中的列表也將不得不保存或單獨記錄在每個腳本的配置文件中。
我假設,多個服務器,可以同時運行的多個腳本以及需要很長或短時間才能完成的腳本。
如何獲得腳本工作的結果也會影響您選擇用於與每個服務器通信的方法,您可能必須根據腳本結果的性質使用不同的方法。