在python 2中每n毫秒定期在python中执行一个函数

sur*_*rya 5 python python-multithreading

我想知道如何在Python中每10毫秒执行一个函数。我尝试使用线程(使用threading.Timer(0.001, fun)),但threading.Timer只能正确执行最多几秒钟。是否有在毫秒(毫秒)内执行任务/函数的方法?

代码如下。

def task():
    print "called every 10ms"
    print time.ctime()
    threading.Timer(0.01,task).start()

task()
Run Code Online (Sandbox Code Playgroud)

Dan*_*auf 3

我自己尝试了一下,确实有效,但是Python在控制台上似乎没有那么快。就我而言,每秒运行次数约为 60 次。

import threading
import time

def hello(*args):
    print(str(args[0])+" It's "+str(time.ctime()))
    next=int(args[0])+1
    threading.Timer(0.001, hello,[str(next)]).start()

hello("1")
Run Code Online (Sandbox Code Playgroud)