【问题标题】:Python realtime timerPython 实时计时器
【发布时间】:2014-05-09 16:46:27
【问题描述】:

有人可以建议我将 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() 过程

in start raise RuntimeError("线程只能启动一次") RuntimeError: 线程只能启动一次

【问题讨论】:

  • 根据您需要的精确程度,您可以使用time module 获得一些东西,但这取决于系统(因此它并不总是正确)
  • @wnnmaw erm 只是一个计数器,当它超过它会做某事的值时,它会计数 1,2,3,4,5,6。当函数被调用时,它将再次重置计数
  • 是的,这就是计数器......你仍然可以使用time
  • @DanvinLeeQicheng 我用你最近一期的答案更新了我的答案。
  • @dano 感谢您的回答,但我的 def 输出还有一个问题:我需要重置并再次调用计时器以使 t 全局且可供所有人访问

标签: python timer counter


【解决方案1】:

我建议使用time module 来处理这样的事情:

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$ 

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

>>> 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()
>>> 

【讨论】:

  • 我不知道我是否会称编辑您的错误答案以包含其他人的正确答案“它是如何完成的”,但我想每个人都有自己的答案。
【解决方案2】:

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    相关资源
    最近更新 更多