I'm new in the world of Javascript coding.
I've managed to adapt some javascript code to edit a Google Sheet. However, I'd want to create a time-driven trigger that runs this code every day, with date exceptions (e.g. not in the weekend, winter/easter holidays, ...). The date exceptions don't have to carry the year, because this exceptions must be applied every year.
for example:
create "time-driven trigger" --> run code "every day from 7am to 8am" - { every Sunday , from 12/25 to 01/10 , 07/04 }
Is it possible to widen the possibilities of AppsScript triggers to what I'd want to achieve?
Any help would be much appreciated.
Time-driven trigger settings: https://drive.google.com/file/d/1sexjgI1YPNuJBVt5riBa-Nfa5AZ8FVR9/view?usp=sharing
Cross-posted over another forum: https://www.excelforum.com/for-other-platforms-mac-google-docs-mobile-os-etc/1391042-execution-of-appsscript-trigger-with-date-exceptions.html
CodePudding user response:
To run your doStuff_()
function every day except weekends and holidays, use a time-driven trigger to run a helper function that checks whether the current date and time are within your time limits, and only call doStuff_()
if it is, like this:
/**
* Run this function on a time-driven trigger once an hour.
* https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers
*/
function onTimeDrivenTrigger(e) {
const timeLimits = {
start: '07:00', // use 24-hour military time; use '' to run without start time limit
end: '08:00', // use 24-hour military time; use '' to run without end time limit
weekdays: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], // use a list like ['Mon', 'Tue'], or [] to run every day
holidays: ['4 Jul', '25 Dec'], // list dates that should be excluded regardless of weekday
};
if (isTimeToRun_(timeLimits)) {
doStuff_();
}
}
/**
* Checks whether the current time is within timeLimits.
*
* @param {Object} timeLimits { start: '07:00', end: '19:00', weekdays: ['Mon', 'Tue'], holidays: ['4 Jul', '25 Dec'] }
* @return {Boolean} true if the current time is within timeLimits, otherwise false.
*/
function isTimeToRun_({ start = '', end = '', weekdays = [], holidays = [] } = {}) {
// version 1.0, written by --Hyde, 12 October 2022
// - see https://stackoverflow.com/a/74044450/13045193
const timestamp = new Date();
const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
const [timeString, weekdayString, dateString] = ['HH:mm', 'EEE', 'd MMM'].map(
format => Utilities.formatDate(timestamp, timezone, format)
);
if (start && timeString < start
|| end && timeString > end
|| weekdays.length && !weekdays.includes(weekdayString)
|| holidays.includes(dateString)) {
return false;
}
return true;
}