gpt4 book ai didi

python - 在类初始化中每 X 秒执行一次函数

转载 作者:太空宇宙 更新时间:2023-11-03 19:21:46 25 4
gpt4 key购买 nike

我创建了一个jabberbot我想广播预定消息的类。我对线程(任何语言)都没有太多经验,但我很难掌握 python 的概念。

我最近的尝试是使用 threading.timer像这样的东西:

class myBot(JabberBot):
def __init__( self, jid, password, res = none):
autoNotify()

def autoNotify():
#Send timed message
self.send('someuser@jabber.example.com','cooool message text!')
#set/reset timer
t = Timer(05,self.autoNotify)
t.start()

这样做的问题是它会不断产生新线程,直到最终死亡。我已经阅读了许多关于使用第三方库、消息队列和twisted 的示例,但我的问题很简单——是否真的没有简单的方法来生成单个异步线程?

最佳答案

Yes, there is .

但是,您确实不应该在构造函数中生成线程。相反,提供一个 run 方法并继承自 threading.Thread,这将使公共(public) start 方法可用,可用于启动通知环形。像这样的事情:

import threading
import time

class myBot(JabberBot, threading.Thread):
def __init__( self, jid, password, res = none):
threading.Thread.__init__(self)

def run(self):
while True:
self.autoNotify()
time.sleep(5) # wait 4 seconds

def autoNotify(self):
self.send('someuser@jabber.example.com','cooool message text!')

像这样使用:

 myBot(...).start()

如果由于某种原因你不能或不想使用多重继承,你也可以这样做:

class myBot(JabberBot):
def start(self):
threading.Thread(target=self.autoNotifyLoop).start()

def autoNotifyLoop(self):
while True:
self.autoNotify()
time.sleep(5) # wait 4 seconds

def autoNotify(self):
self.send('someuser@jabber.example.com','cooool message text!')

您还可以为此创建一个函数,以最大程度地“方便”:

def call_async(func, *args, **kw):
threading.Thread(target=func, args=args, kwargs=kw).start()

def do_something(msg):
print msg

call_async(do_something, "Don't overuse threads!")

关于python - 在类初始化中每 X 秒执行一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com