2016-09-20 65 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

是否线程没有与任何瓶冲突? –