GAS 執行限制與配額 (Quotas and Limits)
雖然 Google Apps Script 是免費的,但為了防止資源濫用,Google 對各項服務設定了每日配額 (Quotas) 與執行限制。了解這些限制能幫助你設計出更強健、不會隨意中斷的自動化系統。
核心執行限制
- 單次執行時間:
- 個人帳戶 (@gmail.com):6 分鐘。
- Google Workspace 帳戶:30 分鐘。
- 每日總觸發器執行時間:約 1 小時 (個人) 或 6 小時 (Workspace)。
如果你的腳本需要處理上萬列資料且超過 6 分鐘,它會拋出
Exceeded maximum execution time 錯誤並直接中斷。解決超時:分段執行 (Segmented Execution)
當資料量太大時,你不能一次性處理完。可以採用「記憶位置 + 自動觸發」的策略:
/**
* 大量資料處理:分段處理範例
*/
function processLargeData() {
const startTime = new Date().getTime();
const properties = PropertiesService.getScriptProperties();
// 1. 讀取上次處理到第幾列
let startRow = parseInt(properties.getProperty('LAST_ROW') || '1');
const sheet = SpreadsheetApp.getActiveSheet();
const lastRow = sheet.getLastRow();
for (let i = startRow; i <= lastRow; i++) {
// 2. 檢查是否快要超時 (設為 5 分鐘)
const currentTime = new Date().getTime();
if (currentTime - startTime > 5 * 60 * 1000) {
// 紀錄目前位置並設定觸發器後中斷
properties.setProperty('LAST_ROW', i.toString());
createNextTrigger();
console.log(`快超時了,紀錄在第 ${i} 列,設定下一次觸發。`);
return;
}
// 執行核心邏輯...
processRow(i);
}
// 3. 全部處理完後,清除紀錄與觸發器
properties.deleteProperty('LAST_ROW');
deleteOldTriggers();
}
function createNextTrigger() {
ScriptApp.newTrigger('processLargeData')
.timeBased()
.after(1 * 60 * 1000) // 1 分鐘後再跑一次
.create();
}
常見服務配額 (每日)
| 服務項目 | 個人帳戶 (@gmail.com) | Google Workspace |
|---|---|---|
| Gmail 寄件人數 | 100 人 / 日 | 1,500 人 / 日 |
| UrlFetch 請求次數 | 20,000 次 / 日 | 100,000 次 / 日 |
| 建立試算表數量 | 250 個 | 限制較寬 |
| 觸發器總執行時間 | 60 分鐘 / 日 | 6 小時 / 日 |
查詢目前配額狀態
你可以透過程式碼隨時檢查剩餘配額。
/**
* 檢查剩餘的寄信配額
*/
function checkQuota() {
const remainingEmails = MailApp.getRemainingDailyQuota();
console.log(`今天還能寄 ${remainingEmails} 封信。`);
}
核心配額相關函數語法說明
- MailApp.getRemainingDailyQuota():回傳當天剩餘可寄送的電子郵件數量。
- new Date().getTime():取得當前 Unix 時間戳記 (毫秒),用於計算腳本已執行多久。
- ScriptApp.getProjectTriggers():取得本專案所有觸發器,可用於清理過期的動態觸發器。
掌握配額限制是將 GAS 應用於生產環境 (Production) 的必經之路,確保你的自動化流程在 Google 的規範下穩定運行。