gpt4 book ai didi

python - 使用带有 gunicorn 的flask_apscheduler

转载 作者:行者123 更新时间:2023-12-03 16:00:44 27 4
gpt4 key购买 nike

我正在尝试在我的 Flask 应用程序中安排任务时不时触发......这对 Flask 开发服务器非常有效,但是一旦我用 gunicorn 触发同一个应用程序它没有按预期工作,没有错误,但没有触发任何任务..

from flask import Flask
from flask_apscheduler import APScheduler


class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'myapp:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 5
}
]

SCHEDULER_API_ENABLED = True


def job1(a, b):
print(str(a) + ' ' + str(b))

app = Flask(__name__)

if __name__ == '__main__':
app.config.from_object(Config())

scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()

app.run()

为此,我包含了这个示例, python myapp.py工作正常并打印 1 2然而,每五秒运行一次 gunicorn -w 1 -b 0.0.0.0:5000 myapp:app不打印 1 2每五秒一次,为什么?

最佳答案

所以,两件事

1)使用日志,你会得到更多的信息:

2)
您需要在if __name__=='__main__':之外申报堵塞:

  1 from flask import Flask
2 from flask_apscheduler import APScheduler
3 import logging
4
5 logging.basicConfig(level=logging.DEBUG,
6 format='%(asctime)s %(levelname)s %(message)s')
7
8 logger = logging.getLogger(__name__)
9
10 class Config(object):
11 JOBS = [
12 {
13 'id': 'job1',
14 'func': 'scratch:job1',
15 'args': (1, 2),
16 'trigger': 'interval',
17 'seconds': 5
18 }
19 ]
20
21 SCHEDULER_API_ENABLED = True
22
23
24 def job1(a, b):
25 logger.info(str(a) + ' ' + str(b))
26
27 app = Flask(__name__)
28 app.config.from_object(Config())
29
30 scheduler = APScheduler()
31 scheduler.init_app(app)
32 scheduler.start()
33
34
35 if __name__ == '__main__':
36 app.run()
~
~

输出:
[2017-02-15 14:29:39 +0000] [25122] [INFO] Booting worker with pid: 25122
2017-02-15 14:29:39,817 INFO Adding job tentatively -- it will be properly scheduled when the scheduler starts
2017-02-15 14:29:39,819 INFO Added job "job1" to job store "default"
2017-02-15 14:29:39,819 INFO Scheduler started
2017-02-15 14:29:39,820 DEBUG Looking for jobs to run
2017-02-15 14:29:39,820 DEBUG Next wakeup is due at 2017-02-15 14:29:44.816072-05:00 (in 4.995362 seconds)
2017-02-15 14:29:44,816 DEBUG Looking for jobs to run
2017-02-15 14:29:44,817 INFO Running job "job1 (trigger: interval[0:00:05], next run at: 2017-02-15 14:29:44 EST)" (scheduled at 2017-02-15 14:29:44.816072-05:00)
2017-02-15 14:29:44,817 INFO 1 2

问题:

这份工作最初并没有被解雇。问题是您的调度程序定义(在您的块内 if __name__ == '__main__' 只有当您直接调用该 python 文件(python myapp.py)时才会命中此代码

当您使用 Gunicorn 启动它时, __name__不再是主要的,它是“myapp.py”,所以它永远不会到达创建和添加调度程序的代码部分:)

关于python - 使用带有 gunicorn 的flask_apscheduler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42257942/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com