Finish a long job in parts (6-minute limit)
Apps Script recipes › Triggers and long jobs
Works through rows until about 5 minutes have passed, remembers where it stopped, and schedules itself to go on.
File Code.gs
const BUDGET_MS = 5 * 60 * 1000;
function startJob() {
PropertiesService.getScriptProperties().setProperty('job_next', '2');
continueJob();
}
function continueJob() {
const started = Date.now();
const props = PropertiesService.getScriptProperties();
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName('Items');
let row = Number(props.getProperty('job_next') || 2);
const last = sheet.getLastRow();
while (row <= last && Date.now() - started < BUDGET_MS) {
// Work on one row (or a small batch of rows) here.
row++;
}
ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() === 'continueJob').forEach(t => ScriptApp.deleteTrigger(t));
if (row <= last) {
props.setProperty('job_next', String(row));
ScriptApp.newTrigger('continueJob').timeBased().after(60 * 1000).create();
return `Stopped at row ${row}; it goes on in a minute.`;
}
props.deleteProperty('job_next');
return 'Done.';
}
Good to know
- Apps Script stops any run after 6 minutes ("Exceeded maximum execution time"); this keeps each run under it.
- Start it with startJob(); it removes its own trigger when everything is done.
Let the AI put it in your appGAS AI Builder knows every recipe here. Describe your app and it uses this code where it fits, in a Google Apps Script project in your own Drive.
Use it in a project