Skip to main content
 首页 » 编程设计

python之GAE : Task on backend instance killed without warning

2025年05月04日7telwanggs

长话短说:

我如何解决 Appengine 中的这个错误:有时 is_shutting_down 返回 False,并在一两秒后关闭实例?

详情

我在 Google Appengine 应用程序 (Python) 上有一个后端实例。后端实例用于生成报告,有时需要几分钟甚至几小时才能完成。

为了处理意外关闭,我正在监视 runtime.is_shutting_down() 并在 is_shutting_down 返回 True 时将报告的中间状态存储到数据库中。

这是我检查的代码部分:

from google.appengine.api import runtime 
 
#... 
 
def my_report_function(): 
    #... 
    # Check if we should interrupt and reschedule to avoid timeout error. 
    duration_sec = time.time() - start 
    too_long = MAX_SEC < duration_sec 
    is_shutting_down = runtime.is_shutting_down() 
    log.debug('Does this report iteration need to wrap it up soon? ' 
              'Too long? %s (%s sec). Shutting down? %s' 
               % (too_long, duration_sec, is_shutting_down)) 
    if too_long or is_shutting_down: 
        # save the state of report, reschedule next iteration, and return 

有时它可以工作,但有时我会在 Appengine 日志中看到以下内容:

D 2013-06-20 18:41:56.893 Does this report iteration need to wrap it up soon? Too long? False (348.865950108 sec). Shutting down? False  
E 2013-06-20 18:42:00.248 Process terminated because the backend took too long to shutdown. 

很明显,从我检查 runtime.is_shutting_down() 返回的值到 Appengine 终止后端之间,30 秒超时没有过去。

有谁知道为什么会这样,是否有解决方法?

提前致谢!

请您参考如下方法:

此处有来自 Google IO 的演示代码 http://backends-io.appspot.com/

包含的 counter_v3_with_write_behind.py 演示了一种模式:

在 '/_ah/start' 上通过设置一个关闭 Hook

runtime.set_shutdown_hook(something_to_save_progress_and_requeue_task) 

看起来您的代码是“您现在是否正在关机,如果没有,去做一些可能需要一段时间的事情”。此模式应监听“尽快关闭,否则你将失去一切”。