2016-09-20 63 views
0

我用瓶子寫的簡單的應用程序。我需要每10秒運行一次相同的方法。我的第一個想法是這樣的事情,但它不工作,我認爲這是醜陋的解決方案:瓶中的異步動作

inc = 0 
# after run server open /loop page in order do initiate loop 
@route('/loop', method='GET') 
def whiletrue(): 
    global inc 
    inc += 1 
    print inc 
    if inc != 1: 
     return str(inc) 
    while True: 
     time.sleep(1) 
     print "X", 

你可以建議我怎麼做它正確的方式?

回答

1

可以使用線程模塊調用與定時器命令的方法:

from functools import partial 
import threading 

class While_True(threading.Thread): 
    def __init__(self, **kwargs): 
     threading.Thread.__init__(self) 

    def whileTrue(self, *args): 
     print args 

    def caller(self, *args): 
     threading.Timer(10, partial(self.whilTrue, "Hallo")).start() 
+0

是否線程沒有與任何瓶衝突? –