【发布时间】:2013-08-24 16:32:54
【问题描述】:
一些功能应该在网络服务器上异步运行。发送电子邮件或数据后处理是典型的用例。
编写装饰器函数以异步运行函数的最佳(或最 Pythonic)方法是什么?
我的设置很常见:Python、Django、Gunicorn 或 Waitress、AWS EC2 标准 Linux
例如,这是一个开始:
from threading import Thread
def postpone(function):
def decorator(*args, **kwargs):
t = Thread(target = function, args=args, kwargs=kwargs)
t.daemon = True
t.start()
return decorator
期望的用法:
@postpone
def foo():
pass #do stuff
【问题讨论】:
-
看看这个帖子stackoverflow.com/questions/573618/…。对于计划的作业,请选择基于 cron 的解决方案。 Scheduled Job, Asynchronous tasks 选择 Celery。在最近迁移到 Celery 之前,我从 github.com/tivix/django-cron 开始。
-
感谢到目前为止的所有答案,但是 Celery 需要相当多的开销(安装应用程序,为其创建数据库)。因此,虽然 Celery 是一个解决方案,但它并没有回答我关于编写独立装饰器来多线程函数的问题。
标签: python django multithreading decorator python-multithreading