Python线程-如何在单独的线程中重复执行函数?

Python线程-如何在单独的线程中重复执行函数?,python,multithreading,timer,setinterval,Python,Multithreading,Timer,Setinterval,我有以下代码: import threading def printit(): print ("Hello, World!") threading.Timer(1.0, printit).start() threading.Timer(1.0, printit).start() 我试图每秒打印一次“Hello,World!”,但是当我运行代码时,什么都没有发生,这个过程只是保持活动状态 我读过一些帖子,上面的代码确实适用于人们 我很困惑在python中设置一个合适的间隔有多么困难,因为

我有以下代码:

import threading
def printit():
  print ("Hello, World!")
  threading.Timer(1.0, printit).start()
threading.Timer(1.0, printit).start()
我试图每秒打印一次“Hello,World!”,但是当我运行代码时,什么都没有发生,这个过程只是保持活动状态

我读过一些帖子,上面的代码确实适用于人们

我很困惑在python中设置一个合适的间隔有多么困难,因为我已经习惯了JavaScript。我觉得我错过了什么


非常感谢您的帮助。

我在Python3.6中运行它。它的工作原理与您的预期一致。

我在Python3.6中运行它。它的工作原理与您的预期一致。

我认为您当前的方法没有任何问题。它在Python2.7和3.4.5中都适用

import threading

def printit():
    print ("Hello, World!")
    # threading.Timer(1.0, printit).start()
    #  ^ why you need this? However it works with it too

threading.Timer(1.0, printit).start()
其中打印:

Hello, World!
Hello, World!
但我建议以以下方式开始线程:

thread = threading.Timer(1.0, printit)
thread.start()
以便您可以使用以下命令停止线程:

thread.cancel()
如果没有对象到类,则必须关闭解释器才能停止线程


替代方法:

就我个人而言,我更喜欢通过将类扩展为以下方式来编写计时器线程:

from threading import Thread, Event

class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("Thread is running..")
my_event = Event()
thread = MyThread(my_event)
thread.start()
然后以类的对象作为开始线程:

from threading import Thread, Event

class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("Thread is running..")
my_event = Event()
thread = MyThread(my_event)
thread.start()
您将开始在屏幕中看到以下输出:

Thread is running..
Thread is running..
Thread is running..
Thread is running..
要停止线程,请执行:

my_event.set()

这为将来修改更改提供了更大的灵活性。

我认为您当前的方法没有任何问题。它在Python2.7和3.4.5中都适用

import threading

def printit():
    print ("Hello, World!")
    # threading.Timer(1.0, printit).start()
    #  ^ why you need this? However it works with it too

threading.Timer(1.0, printit).start()
其中打印:

Hello, World!
Hello, World!
但我建议以以下方式开始线程:

thread = threading.Timer(1.0, printit)
thread.start()
以便您可以使用以下命令停止线程:

thread.cancel()
如果没有对象到类,则必须关闭解释器才能停止线程


替代方法:

就我个人而言,我更喜欢通过将类扩展为以下方式来编写计时器线程:

from threading import Thread, Event

class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("Thread is running..")
my_event = Event()
thread = MyThread(my_event)
thread.start()
然后以类的对象作为开始线程:

from threading import Thread, Event

class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("Thread is running..")
my_event = Event()
thread = MyThread(my_event)
thread.start()
您将开始在屏幕中看到以下输出:

Thread is running..
Thread is running..
Thread is running..
Thread is running..
要停止线程,请执行:

my_event.set()

这为将来修改更改提供了更大的灵活性。

我使用了Python 3.6.0。
我用的是线程和时间包

import time
import _thread as t
def a(nothing=0):
    print('hi',nothing)
    time.sleep(1)
    t.start_new_thread(a,(nothing+1,))
t.start_new_thread(a,(1,))#first argument function name and second argument is tuple as a parameterlist.
o/p将类似于
你好1
嗨2
你好3

..

我使用了Python 3.6.0。
我用的是线程和时间包

import time
import _thread as t
def a(nothing=0):
    print('hi',nothing)
    time.sleep(1)
    t.start_new_thread(a,(nothing+1,))
t.start_new_thread(a,(1,))#first argument function name and second argument is tuple as a parameterlist.
o/p将类似于
你好1
嗨2
你好3

..

可能存在的问题是,每次运行printit时都会创建一个新线程

更好的方法可能是创建一个线程,该线程执行您希望它执行的任何操作,然后在由于某种原因完成时发送和事件以停止它:

from threading import Thread,Event
from time import sleep

def threaded_function(evt):
    while True: # ie runs forever
        if evt.isSet():
            return()
        print "running"
        sleep(1)


if __name__ == "__main__":
    e=Event()
    thread = Thread(target = threaded_function, args = (e, ))
    thread.start()
    sleep(5)
    e.set() # tells the thread to exit
    thread.join()
    print "thread finished...exiting"

可能存在的问题是,每次运行printit时都会创建一个新线程

更好的方法可能是创建一个线程,该线程执行您希望它执行的任何操作,然后在由于某种原因完成时发送和事件以停止它:

from threading import Thread,Event
from time import sleep

def threaded_function(evt):
    while True: # ie runs forever
        if evt.isSet():
            return()
        print "running"
        sleep(1)


if __name__ == "__main__":
    e=Event()
    thread = Thread(target = threaded_function, args = (e, ))
    thread.start()
    sleep(5)
    e.set() # tells the thread to exit
    thread.join()
    print "thread finished...exiting"

这个片段对我很有用。看看这个在线python编译器,问题似乎出在我的git bash上。奇怪,这个片段对我有用。看看这个在线python编译器,问题似乎出在我的git bash上。奇怪,你的例子不是只有一次吗?作为计时器,不是间隔?使用第一种方法,我得到的
组参数现在必须是None
。但您的示例不是只运行一次吗?作为计时器,不是间隔?使用第一种方法,我得到的
组参数现在必须是None