"是否可以在Google App Engine中增加响应超时时间?"

2024-09-21 17:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的本地机器上,脚本运行得很好,但在云端,它一直运行500次。这是一个cron任务,所以我不介意它需要5分钟。。。在

<;类'谷歌.appengine.runtime.DeadlineExceedError'>;:

你知道是否可以增加超时时间吗?在

谢谢, 芮


Tags: ltgt脚本机器时间cronruntime云端
3条回答

DB query超时的确切规则很复杂,但似乎一个查询的生存时间不能超过2分钟,而一个批处理的生存时间不能超过30秒。下面是一些代码,它将一个作业分解为多个查询,使用游标来避免这些超时。在

def make_query(start_cursor):
  query = Foo()

  if start_cursor:
    query.with_cursor(start_cursor)

  return query

batch_size = 1000
start_cursor = None

while True:
  query = make_query(start_cursor)
  results_fetched = 0

  for resource in query.run(limit = batch_size):
    results_fetched += 1

    # Do something

    if results_fetched == batch_size:
      start_cursor = query.cursor()
      break
  else:
    break

下面是我用来解决这个问题的代码,通过将一个大查询分解成多个小查询。我使用google.appengine.ext.ndb库,我不知道下面的代码是否需要它。在

(如果您不使用ndb,请考虑切换到它。它是db库的改进版本,迁移到它很容易。有关详细信息,请参见https://developers.google.com/appengine/docs/python/ndb。)

from google.appengine.datastore.datastore_query import Cursor

def ProcessAll():
  curs = Cursor()
  while True:
    records, curs, more = MyEntity.query().fetch_page(5000, start_cursor=curs)
    for record in records:
      # Run your custom business logic on record.
      RunMyBusinessLogic(record)
    if more and curs:
      # There are more records; do nothing here so we enter the 
      # loop again above and run the query one more time.
      pass
    else:
      # No more records to fetch; break out of the loop and finish.
      break

您不能超过30秒,但可以通过使用任务队列来间接地增加超时时间,并编写逐步遍历数据集并对其进行处理的任务。当然,每次这样的任务运行都应该符合超时限制。在

编辑

更具体地说,可以使用数据存储查询游标在同一位置恢复处理:

http://code.google.com/intl/pl/appengine/docs/python/datastore/queriesandindexes.html#Query_Cursors

在SDK 1.3.1中首次引入:

http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html

相关问题 更多 >