【问题标题】:passing arguments when scheduling a function with asyncio/aiocron使用 asyncio/aiocron 调度函数时传递参数
【发布时间】:2016-08-17 18:26:12
【问题描述】:

我正在使用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 显然不知道或不关心它调用的函数在哪个类中。这使得 aiocron 在我的情况下相当无用,这是一种耻辱。有什么方法可以在aiocron 调用的函数中获取self

【问题讨论】:

  • 我可以说这是一个糟糕的设计库,请永远不要使用它。它不适用于非默认事件循环。此外,您无法正确处理crontab 方法引发的错误,除非您将每个方法都包装在try/finally 块中。所有问题的单一处理程序都没有错误,这在实践中非常烦人。
  • @AndrewSvetlov 你对我应该改用什么有什么建议吗?
  • 我相信通过await asyncio.sleep(...) 编写自己的循环并在一定延迟内休眠我可以解决您的问题,而无需额外的库。
  • @AndrewSvetlov ...但是我需要重新发明 aiocron/croniter 已经做的所有事情
  • 如果轮子不是圆的,不要害怕重新发明轮子。

标签: python python-3.x python-asyncio


【解决方案1】:

我现在通过使用闭包自己解决了这个问题:

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 以保持代码更简洁

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2011-12-20
    • 2018-12-13
    相关资源
    最近更新 更多