在python中没有线程的定时器?

时间:2016-07-26 07:25:12

标签: python multithreading

我是编程新手,想添加一个计数器,每两秒从你的分数中扣除1分。 (所以我必须迅速回答才能提高分数)

chr
import random
import time
radians2 = None
ans = None
score = 0

radians1 = ['0', 'π/6', 'π/3', 'π/4', 'π/2', '2π/3', '3π/4', '5π/6', 'π', '7π/6', '4π/3', '5π/4', '3π/2', '5π/3', '7π/4', '11π/6', '2π']
while radians2 == ans or ans == None:

radians3 = (random.choice(radians1))
ans = input(radians3)
if radians3 == '0':
    radians2 = 0

elif radians3 == 'π/6':
    radians2 = 30

elif radians3 == 'π/3':
    radians2 = 60

elif radians3 == 'π/4':
    radians2 = 45

elif radians3 == 'π/2':
    radians2 = 90

elif radians3 == '2π/3':
    radians2 = 120

elif radians3 == '3π/4':
    radians2 = 135

elif radians3 == '5π/6':
    radians2 = 150

elif radians3 == 'π':
    radians2 = 180

elif radians3 == '7π/6':
    radians2 = 210

elif radians3 == '4π/3':
    radians2 = 240

elif radians3 == '5π/4':
    radians2 = 225

elif radians3 == '3π/2':
    radians2 = 270

elif radians3 == '5π/3':
    radians2 = 300

elif radians3 == '7π/4':
    radians2 = 315

elif radians3 == '11π/6':
    radians2 = 330

elif radians3 == '2π':
    radians2 = 360
score = score + 1

if radians2 == ans:
    print('Correct!')
    print "You've got %d in a row" % score
print "You lose, the correct answer was %d" % radians2

很抱歉,如果代码很乱/很长 我发现我想基本上运行类似的东西:

while 1:
     time.sleep(2)
     score = score - 1

唯一的问题是,它不会与程序的其余部分同时运行,并且线程(这似乎是替代方案)对我来说非常困惑。

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码启动新线程,并在其run()方法中编写您的功能逻辑。

-fPIC

以上代码将迭代直到线程可运行(self.runable = True),因此在2秒后得分将减1并且run方法中的循环将中断,并将终止。

所以,为了调用上面的线程,请执行此操作。

import threading
import time

class RepeatEvery(threading.Thread):
    def __init__(self, interval):

        threading.Thread.__init__(self)     
        self.interval = interval  # seconds between calls
        self.runable = True

    def run(self):
        global score # make score global for this thread context
        while self.runable:
            time.sleep(self.interval)
            if self.runable:     
                score = score - 1
                self.runable = False

    def stop(self):
        self.runable = False

这将调用线程构造函数 init ,并将使用2秒或从此处传递的任何值初始化interval变量。

为了同时停止线程,只需调用stop()方法。

score_thread = RepeatEvery(2)
score_thread.start()    

您也可以调用join()方法,等待线程完成它的执行。

score_thread.stop() 

看起来不那么令人困惑:)

答案 1 :(得分:1)

如果您不想使用任何线程,可以使用corutine,每次调用生成器的下一个方法时,它都会产生经过的时间:

def timer():
    prev_time = new_time = 0
    while True:
        prev_time, new_time = new_time, time.clock()
        time_delta = new_time - prev_time
        yield time_delta

>>> t = timer()
>>> t.next()
4.399568842253459e-06
>>> t.next()
1.7571719571481994
>>> t.next()
0.8449679931366727