Notify Once

An hourly trigger checks a condition and emails you when it is true. Without a guard you get the same email every hour until someone fixes it. notifyOnce(key, sendFn) runs sendFn the first time only and records that it did. resetNotify(key) clears the flag once things are back to normal, so the next problem alerts again.

When to use

  • Low-stock, over-budget, or missing-data warnings on a timed trigger
  • Any "tell me when X happens" check that runs more often than X changes

How to use this snippet

/** * Run sendFn once per key until resetNotify(key) is called. * Flags live in Script Properties, so they survive between trigger runs. * * @param {string} key what this alert is about, e.g. 'low-stock-SKU42' * @param {Function} sendFn sends the alert * @return {boolean} true if the alert was sent this time */ function notifyOnce(key, sendFn) { var props = PropertiesService.getScriptProperties(); var flag = 'notified_' + key; if (props.getProperty(flag)) return false; sendFn(); props.setProperty(flag, new Date().toISOString()); return true; } function resetNotify(key) { PropertiesService.getScriptProperties().deleteProperty('notified_' + key); }

Example

function checkStock() { var qty = SpreadsheetApp.getActive().getRangeByName('StockSKU42').getValue(); if (qty < 10) { notifyOnce('low-stock-SKU42', function () { MailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'Low stock: SKU42', 'Only ' + qty + ' left.'); }); } else { resetNotify('low-stock-SKU42'); } }

Notes

  • Use one key per thing you watch, so one alert doesn't silence another.
  • The flag is set only after sendFn returns, so a failed send is tried again on the next run.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension