Python 实时计时器

0 投票
2 回答
7940 浏览
提问于 2025-04-18 06:01

有没有人能帮我把Java的Timer类转换成Python?我现在正在把一个Java程序转换成Python脚本。不过,Python似乎没有Timer/TimerTask这个库(如果有的话,请告诉我。谢谢!)。我需要能够重置这个计时器。Java有Timer.cancel这个方法,但Python没有。有没有什么可以替代的?

            timer.cancel();
            timer = new Timer("Printer");
            MyTask t = new MyTask();
            timer.schedule(t, 0, 1000);

Java脚本计时器

    class Timerclass extends TimerTask {
    //times member represent calling times.
    private int times = 0;


    public void run() {
        times++;
        if (times <= 5) {
             System.out.println(""+times);
        } else {
            this.cancel();
            //Stop Timer.
            System.out.println("Timer Finish");

        }

    }
}

这是我目前的代码

import time
import threading

class Variable:
    count = 0
    people = 0
    times = 0

def enter():
    if int(Variable.count == 1):
        print("Entered")
        t = threading.Timer(5.0, countdown)
        t.start()
    else:
        print("Entered +1")
        t.clear() // Stuck Help 
        t = threading.Timer(5.0, countdown)
        t.start()
def out():
    if int(Variable.count > 0):
        print("Exited")
    elif int(Variable.count < 0):
        print("Error")

def countdown():
    print("TIMEUP")

while True:
    sensor1 = input("Sensor 1: ")
    sensor2 = input("Sensor 2: ")
    Variable.count+=1

    if int(sensor1) == int(sensor2):
        Variable.count -= 1
        print(Variable.count)
        print("error")
    elif int(sensor1) == 1:
        Variable.people += 1
        print(Variable.people)
        enter()
    elif int(sensor2) == 1:
        Variable.people -= 1
        print(Variable.people)
        out()
    else:
        print("Error")

我遇到一个问题,我需要停止当前的计时并在每次调用这个方法时重新开始。

基本上,我想要的是当我再次调用这个方法时,它能重置或取消任何现有的计时,然后重新计数。

最新更新

import time
import threading

class Variable:
    count = 0
    people = 0
    times = 0

def countdown():
    print("TIMEUP")

t = threading.Timer(5.0, countdown)   
def enter():
    if int(Variable.count == 1):
        print("Entered")
        t.start()
    else:
        print("Entered +1")
        t.cancel()
        t.join()         # here you block the main thread until the timer is completely stopped
        t.start()

def out():
    if int(Variable.count > 0):
        print("Exited")
    elif int(Variable.count < 0):
        print("Error")

while True:
    sensor1 = input("Sensor 1: ")
    sensor2 = input("Sensor 2: ")
    Variable.count+=1

    if int(sensor1) == int(sensor2):
        Variable.count -= 1
        print(Variable.count)
        print("error")
    elif int(sensor1) == 1:
        Variable.people += 1
        print(Variable.people)
        enter()
    elif int(sensor2) == 1:
        Variable.people -= 1
        print(Variable.people)
        out()
    else:
        print("Error")

有没有人能发现我的错误?我遇到了这个错误,但我用t.clear()清除了进程。

在开始时抛出RuntimeError("线程只能启动一次")

RuntimeError: 线程只能启动一次

2 个回答

1

我建议你使用time模块来做这样的事情:

from time import time, sleep
from datetime import datetime, timedelta

nowtime = time()

#Put your script here
x = 1
for k in range(1000):
        x+=1
        sleep(0.01)

sec = timedelta(seconds=int(time()-nowtime))
d = datetime(1,1,1)+sec

print("DAYS:HOURS:MIN:SEC")
print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))

这个代码的作用是,在一开始把时间(以秒为单位)存储到一个变量里,然后在主程序运行完后,把之前的时间和现在的时间相减,最后把结果格式化成天、小时、分钟和秒。

下面是它运行的样子:

bash-3.2$ python timing.py
DAYS:HOURS:MIN:SEC
0:0:0:10
bash-3.2$ 

你也可以使用线程模块(Threading),它里面有一个内置的取消方法:

>>> import threading
>>> def hello():
...     print "This will print after a desired period of time"
... 
>>> timer = threading.Timer(3.0, hello)
>>> timer.start() #After 3.0 seconds, "This will print after a desired period of time" will be printed
>>> This will print after a desired period of time

>>> timer.start()
>>> timer = threading.Timer(3.0, hello)
>>> timer.start()
>>> timer.cancel()
>>> 
1

其实,Python有一个专门的类可以做到这一点,它里面有一个叫做cancel的方法:threading.Timer。这个类和Java的Timer类挺相似的,正好可以满足你的需求(Java的Timer也是在后台线程中运行)。下面是文档中的一个示例用法:

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed

补充:

你更新后的代码有个问题,就是你试图多次使用同一个Timer对象。在Java中可能可以这样做,但在Python中,你不能重复使用一个Thread对象(TimerThread的一个子类)。你需要在调用join()之后,创建一个新的Timer对象。可以这样做:

t = threading.Timer(5.0, countdown)   
def enter():
    global t  # You need this to tell Python that you're going to change the global t variable. If you don't do this, using 't = ..' will just create a local t variable.
    if int(Variable.count == 1):
        print("Entered")
        t.start()
    else:
        print("Entered +1")
        t.cancel()
        t.join()         # here you block the main thread until the timer is completely stopped
        t = threading.Timer(5.0, countdown)
        t.start()

撰写回答