在 google-app-engine 上同时推迟许多任务

defer many tasks simultaneously on google-app-engine

我正在 google 应用引擎上开发一个 python 应用。我有一个 CRON 作业,它每天将 20 个新文件的列表从 S3 存储桶导入 GS 存储桶。

这是我的代码:

import webapp2
import yaml
from google.appengine.ext import deferred

class CronTask(webapp2.RequestHandler):

    def get(self):
        with open('/my/config/file') as file:
            config_dict = yaml.load(file_config_file)
        for file_to_load in config_dict:
            deferred.defer(my_import_function, file_to_load)


app = webapp2.WSGIApplication([
    ('/', CronTask)
], debug=True)

请注意 my_import_function 是另一个包的一部分,需要一些时间才能完成。

我的问题:使用函数 deferred.defer 来完成这项任务是个好主意,还是我应该以不同的方式为所有参数启动 my_import_function

您应该使用任务队列,但根据您有多少任务,您可能不想使用 deferred.defer()

使用deferred.defer(),每次调用只能将一项任务加入队列。如果你正在排队很多任务,那真的很低效。这真的很慢:

for x in some_list:
    deferred.defer(my_task, x)

任务多的话,这样做效率会高很多:

task_list = []
for x in some_list:
    task_list.append(taskqueue.Task(url="/task-url",params=dict(x=x)))
taskqueue.Queue().add(task_list)

大约一年前,我做过时序对比,后者至少比前者快一个数量级。