doPost(e)如何立即响应HTTP 200 OK,然后执行长时间功能

时间:2018-09-21 10:58:46

标签: google-apps-script http-headers

在Google App脚本中,需要在3秒内发送HTTP接收到的代码。

如果没有3秒超时:

function doPost(e) {
    //do stuff
    long_time_function ();
    //can response received simply with this
    //this will auto response received HTTP code: 200 to the request
    return ContentService.createTextOutput(); 
}  

现在需要3秒的超时时间:如果未发送HTTP接收到的代码,则在3秒内,等待的服务器将触发错误。

function doPost(e) {
    //quickly response received?
    //then do stuff
    function longtime() {//long time job }
}

我尝试使用Google搜索,但没有使用外部库就找不到任何解决方法:

我尝试过:

    function doPost(e) {
        //using
        ContentService.createTextOutput();
        //or tried with UrlFetchApp
        UrlFetchApp.fetch(response_url, ops);

        Utilities.sleep(8000);//test
       //then do stuff
        function longtime() {//long time job }
    }

但是仍然不能完全满足3s超时要求。

1 个答案:

答案 0 :(得分:0)

当前,Google Apps脚本不支持异步执行。如果您可以将长时间运行的功能延迟一分钟或2分钟,那么我建议您解决一下。 在doPost内部,创建一个时间驱动的触发器,该触发器将在1或2分钟后运行一个函数,然后立即返回响应。 由于现在已创建触发器,因此它将在计划的时间自动执行该功能。

这是代码的概要。

function longRunningFunction(){
  // Some code here to execute later
}

function doPost(e) {

  var now  = new Date();
  now.setMinutes(now.getMinutes()+2);
  ScriptApp.newTrigger('longRunningFunction').timeBased().at(now).create();

  return ContentService.createTextOutput('My Respnse')
}