Augh, again 😩 Service using too much computer time for one day
I use minute triggers a lot in Google Apps Script projects. This type of task runs repeatedly each minute, so I can control the time to run my code:
if (((minute+3) % 15) == 0) { /* do this */ }
if (minute === 47) { /* do that*/ }
if (hour === 1 && minute === 4) { /* do those */ }
When I add multiple tasks for my minute trigger, it’s not easy to control quotas on daily code runtime. Feel like a blind when hundreds of error messages came to my email. I had a lot of questions and I’ve answered them with a dashboard:
My questions were:
- Do all my functions run well?
- When do I reach the limit?
- What functions take more and need optimization?
- What is the percentage of successfully completed tasks?
I’ve decided to create a code for monitoring each of my onMinute execution and to write the result into memory. The resulting code is here.
To use this code, your first step is to copy/paste the code to the project where your onMinute trigger runs. Then you’ll need to embed the code into trigger functions:
// runs each minute
function onMinute_admin(e)
{
// [ 1 ]. Add these 2 lines
var timer = Timer_('onMinute_admin');
var executionId = timer.start('Started!'); // your useful code here // [ 2 ]. Add this line
timer.end(executionId, 'Done!');}
The code becomes more helpful if you add more meaningful notes instead of Started!
and Done!
.
When your trigger runs, it will also write your logs into script memory. Each minute you’ll have a log like this:
{
"start": "2021-04-21T11:17:12.250Z",
"end": "2021-04-21T11:17:12.412Z",
"time": 162,
"startNote": "Started!",
"endNote": "Done!"
}
In this way, you’ll have all your stats. If the function did not finish, you’ll also see it, as your log will look differently:
{
"start": "2021-04-21T11:17:12.250Z",
"time": 0,
"startNote": "Started!",
}
Reading logs may become a hard part, and that’s why I’ve created a function to retrieve grouped stats by:
- Trigger Tag, like
onMinte_Admin
- Day
- Hour
- Stat Note
- End Note
Metrics are:
- The number of executions started
- The number of executions ended
- Time in milliseconds.
That’s it! My code saves logs of 3 past days, which I thought was enough for my needs. You may change this number, it is stored in the variable called daysToKeep
.
Thank you and happy coding!