import logging import time from threading import Thread def process(): while True: try: if len(queue) > 0: fn = queue.pop() fn() except Exception as e: logging.error(e) finally: time.sleep(1) # 使用 gunicorn 时, gunicorn 会 fork 出若干个子进程, 每个进程都有自己的 worker_thread, 且内存不共享 worker_thread = None queue = [] def submit(job, callback): global worker_thread if worker_thread is None: worker_thread = Thread(target=process) worker_thread.start() queue.append(lambda: job(callback))