This is a sample script for opening and closing Google Forms on time using Google Apps Script.
In order to test this sample script, please do the following flow.
Please create a new Google Form and set your sample questions. And, please open the script editor of Google Form.
Please copy and paste the following script to the script editor of Google Form. And, please set the values of start
and end
times you want.
// Please set start and end time you want.
// In this case, Google Form is opened and closed at the start time and the end time, respectively.
// The script is run every day.
const obj = { start: "09:00", end: "17:00" };
const deleteTriggers_ = (e) =>
ScriptApp.getProjectTriggers().forEach((t) => {
if (e.includes(t.getHandlerFunction())) ScriptApp.deleteTrigger(t);
});
const start = (_) => FormApp.getActiveForm().setAcceptingResponses(true);
const end = (_) =>
FormApp.getActiveForm()
.setAcceptingResponses(false)
.setCustomClosedFormMessage("Closed.");
function installTimeDrivenTrigger() {
deleteTriggers_(["start", "end"]);
const time1 = new Date();
time1.setHours(...obj.start.split(":").map((e) => Number(e)), 0);
const time2 = new Date();
time2.setHours(...obj.end.split(":").map((e) => Number(e)), 0);
ScriptApp.newTrigger("start").timeBased().at(time1).create();
ScriptApp.newTrigger("end").timeBased().at(time2).create();
}
// Please run this script. By this, installTimeDrivenTrigger() is run 00:00 - 01:00 every day.
function init() {
deleteTriggers_(["installTimeDrivenTrigger"]);
ScriptApp.newTrigger("installTimeDrivenTrigger")
.timeBased()
.everyDays(1)
.atHour(0)
.create();
}
-
When you use this script, please run
init()
function with the script editor. -
By this,
installTimeDrivenTrigger()
is installed as a time-driven trigger. This trigger automatically runs the functioninstallTimeDrivenTrigger()
every day. When this function is run,start()
andend()
functions are installed as the time-driven trigger using your inputted times. -
This cycle is run every day by the installed
installTimeDrivenTrigger()
. When this function is run,start()
andend()
functions are installed as the time-driven trigger. -
In this sample, when the user accesses the Google Form from
end
time tostart
time, "Closed." is shown. If you want to change this message, please modify the above script.
- I believe that this sample script for using the time-driven trigger will be useful for other situations.
- newTrigger(functionName)
- deleteTrigger(trigger)
- setAcceptingResponses(enabled)
- setCustomClosedFormMessage(message)
- I answered this sample script in this thread on Stackoverflow.