我有以下应用程序运行调度程序以定期更新全局变量(dict)的状态:
from sanic import Sanic
from sanic.response import text
from apscheduler.schedulers.background import BackgroundScheduler
import bumper
app = Sanic()
scheduler = BackgroundScheduler()
inventory = {1: 1, 2: 2}
@scheduler.scheduled_job('interval', seconds=5)
def bump():
bumper.bump()
@scheduler.scheduled_job('interval', seconds=10)
def manual_bump():
global inventory
inventory[2] += 1
@app.route("/")
async def test(request):
return text(inventory)
if __name__ == "__main__":
scheduler.start()
app.run(host="0.0.0.0", port=8000)
5秒间隔作业中导入的函数在同一目录下的不同文件中:
from app import inventory
def bump_inventory():
inventory[1] += 1
print('new', inventory)
然而,这并没有像我希望的那样工作。导入的函数会更新清单,但更改永远不会传播到原始字典,因此要么bump_inventory
正在处理副本,inventory
要么永远不会在函数范围之外更新它。在两个不同的终端:
]$ python app.py
2017-02-19 14:11:45,643: INFO: Goin' Fast @ http://0.0.0.0:8000
2017-02-19 14:11:45,644: INFO: Starting worker [26053]
new {1: 2, 2: 2}
new {1: 3, 2: 2}
]$ while true; do curl http://0.0.0.0:8000/; echo; sleep 1; done
{1: 1, 2: 2}
...
{1: 1, 2: 3}
...
这样做的正确方法是什么?