2012-10-20 20 views

回答

0

例如:

import thread, time 

def takes_a_while(): 

    def print_status(): 
     while True: 
      print i # print current i every two seconds 
      time.sleep(2) 

    status_thread = thread.start_new_thread(print_status,()) 
    for i in xrange(10000000): 
     print '*', 
     time.sleep(0.1) 
    status_thread.exit() 

takes_a_while() 

可以做更好的与装饰或背景,但你有这个想法。

0

调查APScheduler它有一个非常简单的cron类似接口,以特定的时间间隔运行python代码。

http://packages.python.org/APScheduler/

我用它来安排我的一个项目任务,这是非常稳定和测试,很容易扩展,如果需要其他的方式来存储您的工作。

嗯,这是有点矫枉过正,因为我现在回到你的问题,但我会留下它,因为它可能对其他人的其他类似情况有用。

1

您可以通过保持你的东西打印最后一次轨道做到这一点:

last = time.time() 
while inFile.readable(): 
    line = inFile.readLine() 
    now = time.time() 
    if now - last > 2: # seconds 
     print("time up!") 
     last = now 

如果你的文件需要两秒钟以上阅读,那么这个循环将打印time up!每两秒钟。

+0

是的,但我有兴趣知道如何做到这一点与线程,作为一个练习,因为我不知道如何。 – Kache

+1

我不建议用线程来执行这个特定的任务,它只是不必要地使实现复杂化。 (你原来的问题并没有说明你特别想要线程,这就是为什么这个答案存在。) –

+1

我原来的问题在标题中有“如何有线程”。我只是在身体上重复自己的重点。 – Kache

相关问题