【问题标题】:Terminating GAE Python Background Threads终止 GAE Python 后台线程
【发布时间】:2014-01-14 19:19:08
【问题描述】:

关闭 Google App Engine 后台线程的正确方法是什么?我尝试将循环变量设置为 false 并尝试 join() 线程,但无论我尝试什么,我都会收到很多对 _/ah/stop 的调用,最终以“进程终止,因为后端关闭时间过长”结束。

它可以工作,但感觉不是很稳定,有没有更好的方法来关闭它们?

一些代码:

_thread = None`
_should_run = True

def work():
    service = BqClient.getService()
    tabledata = service.tabledata()

    while (_should_run and not runtime.is_shutting_down()):
        try: 
            queue = taskqueue.Queue('stream-queue')
            tasks = queue.lease_tasks(300, 1000)
            ...do stuff and then sleep...

def startStreamThread():
    _thread = BackgroundThread(target = work)
    _thread.start()

def stopStreamThread():
    _should_run = False
    if (_thread and _thread.isAlive()):
        _thread.join(20)

【问题讨论】:

  • 您是否将超时参数传递给您的 join() 调用(默认为无)?喜欢if runtime.is_shutting_down(): your_thread.join(timeout=1.0)
  • 是的,join(5) 并且线程每个循环只休眠 1 秒。但是没有没有试过“运行时”
  • 好的,所以我将后台循环条件从检查变量更改为while (not runtime.is_shutting_down()),现在它运行良好。也许我在 Python 范围内还不够忍者。谢谢@greg
  • 好吧,看来我的幸福还为时过早,有时我还是会得到同样的东西,不清楚它取决于什么
  • 你能提供一些你的代码吗?

标签: google-app-engine python-2.7


【解决方案1】:

在您的代码中,您的线程负责自己的关闭。这是一件好事,因为 BackgroundThread 可以比产生他的请求更长寿。

如果可能,App Engine 会提前 30 秒 通知后端 终止它。

如果循环中的一批工作耗时超过 30 秒,您的线程将无法正常结束。也许您可以尝试减少每个循环中完成的工作量并在您的time.sleep 之前测试runtime.is_shutting_down

while True:
    # Do stuff that need less than 30 sec.
    do_stuff()
    # Check for shutdown or sleep.
    if runtime.is_shutting_down():
        break
    else:
        time.sleep(1)

有时如果可能(想想硬件故障)是不可能的,你的后端会在很短的时间内关闭。

您永远无法避免突然关机。确保它不会破坏您的应用程序逻辑。

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多