突破Vecel網站最大運行10秒的限制

設置Gitee的Webhooks 到Vercel.com 網站後,因爲API只能運行10秒,許多任務沒有辦法正常完成。爲了突破限制,可以採用多次請求來完成任務,8+8+8等, 達到24秒以上。

一、先看一下效果:

 

 二、實現代碼如下:

import buildPage from 'gitee-pages-build';
import fetch from 'node-fetch'
import sleep from 'sleep-anywhere'
import  URLSearchParams  from 'url-search-params'

export default async function handler(req, res) {

  console.log(req.url);
  let currentStep = parseInt(req.query.step || '1');
  let state = req.query.state;
  

 
  await doAction(req); 
  res.status(200).json({step: currentStep, code:0, msg:"ok"}) 
}

async function doAction(req){
  //add your code here...
  console.log('your code here...',new Date())
  await sleep(5000);

  console.log('end code here...',new Date())
  // do next step action to get more cpu time

  let currentStep = parseInt(req.query.step || '1');
  if(currentStep < 3){
    let state = {currentStep:currentStep}
    // start next time ,to get more time
    await doNext(currentStep + 1,  state);
  }
  else{
    console.log('finished...')
  }
  
}

async function doNext(step,state){
  
  let url = process.env.API_PAGE_BUILD_SELF_URI || 'http://localhost:3000/api/pagebuild';
  let query = new URLSearchParams({ step:step , state: JSON.stringify(state)}).toString();
  let queryUri = url + '?' + query;
  console.log('doNext ', queryUri, step, state);
  fetch(queryUri)
  await sleep(1000);
}

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章