在 Huey 中为 periodic_tasks 实施 context_task 的最佳方法是什么?

What is the best way to implement a context_task for periodic_tasks in Huey?

我正在寻找在 Huey 中使用周期性任务实现 Peewee 上下文管理器的最佳方法。普通任务有那个漂亮的小 Huey.context_task() 装饰器,但周期性任务似乎没有任何相似之处。

我假设我只需要在周期性任务中使用(更丑陋的)with 语句是否正确?

应该可以这样做:

from functools import wraps

huey = RedisHuey()
db = PostgresqlDatabase(...)

def db_periodic_task(*args, **kwargs):
    def decorator(fn):
        @wraps(fn)
        def new_task():
            with db:
                fn()
        return huey.periodic_task(*args, **kwargs)(new_task)
    return decorator

@db_periodic_task(crontab('0', '0'))
def my_periodic_task():
    # db will have been opened at start.
    # db will then be closed upon return.