使用 asyncio/aiocron 调度函数时传递参数
passing arguments when scheduling a function with asyncio/aiocron
我正在使用 aiocron
库来安排一天中特定时间的函数调用。这是我想做的事情的一个最小例子。在此示例中,我想每天在 8:00
发送 "good morning" 消息
class GoodMorningSayer:
@asyncio.coroutine
def send_message(text):
#insert fancy networking stuff here
@aiocron.crontab("0 8 * * *")
@asyncio.coroutine
def say_good_morning():
yield from self.send_message("good morning!")
# I don't have self here, so this will produce an error
不幸的是,我无法在我的 say_good_morning
方法中获得 self
,因为 aiocron
显然不知道或不关心 class 它调用的函数是什么in. 这使得 aiocron 在我的情况下相当无用,这是一种耻辱。有什么办法可以在 aiocron
调用的函数中得到 self
吗?
我现在通过使用闭包自己解决了这个问题:
class GoodMorningSayer:
def __init__(self):
@aiocron.crontab("0 8 * * *")
@asyncio.coroutine
def on_morning()
yield from self.send_message("good morning!")
@asyncio.coroutine
def send_message(text):
#insert fancy networking stuff here
在实际程序中,我将其包装在一些样板文件中,最终调用 self.say_good_morning 以保持代码更清晰
我正在使用 aiocron
库来安排一天中特定时间的函数调用。这是我想做的事情的一个最小例子。在此示例中,我想每天在 8:00
class GoodMorningSayer:
@asyncio.coroutine
def send_message(text):
#insert fancy networking stuff here
@aiocron.crontab("0 8 * * *")
@asyncio.coroutine
def say_good_morning():
yield from self.send_message("good morning!")
# I don't have self here, so this will produce an error
不幸的是,我无法在我的 say_good_morning
方法中获得 self
,因为 aiocron
显然不知道或不关心 class 它调用的函数是什么in. 这使得 aiocron 在我的情况下相当无用,这是一种耻辱。有什么办法可以在 aiocron
调用的函数中得到 self
吗?
我现在通过使用闭包自己解决了这个问题:
class GoodMorningSayer:
def __init__(self):
@aiocron.crontab("0 8 * * *")
@asyncio.coroutine
def on_morning()
yield from self.send_message("good morning!")
@asyncio.coroutine
def send_message(text):
#insert fancy networking stuff here
在实际程序中,我将其包装在一些样板文件中,最终调用 self.say_good_morning 以保持代码更清晰