gawel / aiocron

Crontabs for asyncio
MIT License
338 stars 20 forks source link

Using aiocron decorator inside a class? #27

Open Morgon opened 2 years ago

Morgon commented 2 years ago

Pardon the potentially-simple question/issue. Given a simple class, what is preventing aiocron from properly executing the decorated function?

class MyClass:
    @aiocron.crontab('* * * * *')
    async def crontest(self):
        print(datetime.now())

This results in the following error:

Traceback (most recent call last):
  File "[...]/aiocron/__init__.py", line 85, in call_next
    self.call_func()
  File "[...]/aiocron/__init__.py", line 97, in call_func
    self.cron(*args, **kwargs),
TypeError: crontest() missing 1 required positional argument: 'self'

Short of "don't use classes", is there some other structure I can use to utilize the convenient decorator?

gawel commented 2 years ago

I dont see how to make this possible. The decorator expect a ready to use function. In that case you don't know where to find an instance (self)

A solution may be to instanciate an instance before setting the cron:

instance = Myclass()
aiocron.crontab('* * * * *', func=instance.crontest) 

Should work in __init__ too:

class Myclass:
    def __init__(self):
        aiocron.crontab('* * * * *', func=self.crontest)

(not tested)

MrRazamataz commented 2 years ago

Placing it in __init__ should fix this (it did for me).

class cogtest(commands.Cog):
    def __init__(self, client):
        self.client = client

        @aiocron.crontab('0 8 * * *')