Python 计划在 Flask 中不起作用

Python Schedule not work in Flask

我正在将 Schedule 导入 Flask。我的项目包含 WSGI 但是我对 FlaskWSGI 之间的关系知之甚少。现在我有三个主要文件:

我想在服务器启动时启动一个很长的任务。这是wsgi.py的部分:

# -*- coding: utf-8 -*-
from threading import Thread
import test


t = Thread(target=test.job)
t.start()

if __name__ == '__main__':
    ...

如你所见,我启动了一个线程并让工作在 it.Here 中工作是我的 test.py

import schedule


def job():
    schedule.every(1).seconds.do(pr)


def pr():
    print("I'm working...")

我的问题是 job 永远不会启动。

我发现我的 problem.I 从不让计划执行作业。现在 wsgi.py 看起来像这样。

# -*- coding: utf-8 -*-
from threading import Thread
import test

schedule.every(1).seconds.do(test.job)
t = Thread(target=test.run_schedule)
t.start()

if __name__ == '__main__':
    ...

test.py

import schedule
import time

start_time = time.time()


def job():
    print("I'm working..." + str(time.time() - start_time))


def run_schedule():
    while True:
        schedule.run_pending()
        time.sleep(1)

为了在单独的线程中工作,我创建了一个线程,并在该线程中每 1 毫秒循环一次。在循环中,如果超时(在我的例子中是 1 秒),schedule 调用 run_pending 调用 job