![](/img/trans.png)
[英]A countdown timer that runs in the background and interacts with other functions
[英]Creating a timer that runs in the background
我正在制作一个客户端/服务器程序,并且在客户端上我想要一个在GUI上显示运行时间的时钟。 现在,这里有很多关于如何制作时钟/计时器的教程,我想我要讲的就是这一部分。
问题在于,在其余代码执行时,它会在后台运行。 目前,我有一个定时器循环,该代码不会过去,因此它只是开始计数定时器,然后在此之后不执行其他任何操作。 至少要等到计时器停止为止。
我猜我需要找到一种方法使其在后台运行,但是我不知道如何,也找不到答案。 有人建议我应该使用线程/多线程,但这看起来有点复杂,我不太清楚。
有没有更好的方法可以做到呢?
您可以通过从当前时间中减去开始时间来跟踪自某个点以来经过的时间。 然后,您可以使用此值更新计时器值(如果之间还有很多其他代码在运行,则它会变慢,因此您可能需要四舍五入)。
import time
start = time.time()
while doing_stuff:
do_stuff()
GUI.update_timer(time.time() - start)
我看不出线程不是一个好主意的任何原因。 首先,如果您要在代码中运行复杂的计算,则线程可通过在后台串联运行代码和计时器来提高性能。 以下是一些简单的平方函数可以帮助说明我的观点:
import time
import threading
def square():
start_time = time.time()
x = int(input('Enter number: '))
squared = x*x
print('Square is: %s ' %squared)
print('Time elapsed: %s seconds' %(time.time() - start_time))
set_thread = threading.Thread(target=square) #set Thread() to run on square() function
set_thread.start()
#Output:
Enter number: 5
Square is: 25
Time elapsed: 1.4820027351379395 seconds
当然,上面的简单功能可能只需要几秒钟。 计时器在调用函数时开始,并在square()
块中的代码运行后停止。 但是,请设想一下您的代码具有复杂得多的计算的情况,例如将多个值插入数据库或对大量数据进行排序并同时写入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.