2014-02-07 30 views
2

我已經在這個問題上掙扎了大約一個星期的時間去問一個能在幾分鐘內回答問題的人。如何在不退出現有循環的情況下安排任務?

我想運行一個python程序每10秒一次。有很多這類的問題:使用schedtime.sleep將工作Use sched module to run at a given timePython threading.timer - repeat function every 'n' secondsHow to execute a function asynchronously every 60 seconds in Python?

通常情況下的解決方案,但我想開始從cmd2內的計劃過程中,這已經是一個while False循環中運行。 (當你退出cmd2時,它退出這個循環)。因此,當我啓動一個函數重複每10秒,我輸入另一個循環嵌套在cmd2內,我無法輸入cmd2命令。通過退出正在重複該功能的子循環,我只能返回cmd2,因此該功能將停止重複。

明顯的線程化將解決這個問題。我試過threading.Timer沒有成功。也許真正的問題是我不懂線程或多處理。

下面是代碼,大致同構於我正在使用的代碼示例,使用sched模塊,這是我開始工作:

import cmd2 
    import repeated 

    class prompt(cmd2.Cmd): 
    """this lets you enter commands""" 

     def default(self, line): 
      return cmd2.Cmd.default(self, line) 

     def do_exit(self, line): 
      return True 

     def do_repeated(self, line): 
      repeated.func_1() 

凡repeated.py看起來是這樣的:

import sched 
    import time 

    def func_2(sc): 
     print 'doing stuff' 
     sc.enter(10, 0, func_2, (sc,)) 


    def func_1(): 
     s = sched.scheduler(time.time, time.sleep) 
     s.enter(0, 0, func_2, (s,)) 
     s.run() 

回答

1

當我問我能弄明白的問題。不知道爲什麼有時會發生這種情況。

此代碼

def f(): 
    # do something here ... 
    # call f() again in 60 seconds 
    threading.Timer(60, f).start() 

# start calling f now and every 60 sec thereafter 
f() 

從這裏:How to execute a function asynchronously every 60 seconds in Python?

實際工作爲了什麼,我試圖做的。在函數如何作爲threading.Timer中的一個參數被調用時,顯然有一些微妙之處。之前當我在函數後面包括參數和括號時,我得到了遞歸深度錯誤--i.e。該功能不斷地自動調用。

所以如果有其他人有這樣的問題,請注意如何調用threading.Timer(60, f).start()中的函數。如果你寫threading.Timer(60, f()).start()或類似的東西,它可能無法工作。

2

http://docs.python.org/2/library/queue.html?highlight=queue#Queue

可以將背景CMD2以外的隊列對象?可以有一個線程監視隊列並定期從中獲取作業;而cmd2可以自由運行或不運行。當然,處理隊列的線程和隊列對象本身需要位於外部作用域中。

要在特定時間安排某些內容,可以插入一個包含目標時間的元組。或者你可以讓線程定期檢查,如果這足夠好的話。

[編輯,如果你有打算重複的過程,你可以把它在結束它的操作重新排隊本身。]

+0

謝謝你,我不知道隊列。它看起來會做我正在尋找的東西。但是,我發現了threading.Timer(這是從使用它的答案的數量判斷的首選方法)的簡單方法,並在下面進行了概述。 – Wapiti

相關問題