FLighter
FLighter

Reputation: 439

Time-driven triggers scope in Google Script

UPD:

I have a published application as Spreadsheets addon and a few spreadsheets, that use this addon and execute time driven trigger:

ScriptApp.newTrigger("myFunction")
   .timeBased()
   .everyHours(1)
   .create();

All works fine, but I'm a little confused, in what scope does this trigger work?

Since this is a published addon, the script is one and the time driven function is also one, right? As Diego said: "It works with the user scopes of the user who initiated the trigger". Okay, but what about spreadsheets?

I need to write (if trigger sees only this spreadsheet):

function myFunction(){
    var ss = SpreadsheetApp.getActive();
}

Or (if it runs without binding to a specific spreadsheet):

function myFunction(){
    var ss = SpreadsheetApp.openById('<some id>');
}

In other words, when I set the trigger, do I set it only for the current document or for all?

Thanks!

Upvotes: 0

Views: 442

Answers (1)

Diego
Diego

Reputation: 9571

It works with the user scopes of the user who initiated the trigger. Here's how you can check:

  1. Create a User property value i and set it to zero
  2. In a new function, get the user property i, write it to a sheet, increment i and save it back to the property.
  3. Create a trigger so that function runs every minute.
  4. View the spreadsheet as a different user.
  5. As the different user, repeat steps 1 & 2 to see that now i has started again from zero, but the 1-minute trigger is still iterating the original i value (because the different user can't access the first user's properties).

Here's the code:

function getAndPrintUserProperty() {
  var userProperties = PropertiesService.getUserProperties();
  var i = userProperties.getProperty("i");
  i++;
  SpreadsheetApp.getActive().getSheetByName("Sheet1").appendRow([i]);
  userProperties.setProperty("i", i);
}

function addUserProperty() {
  PropertiesService.getUserProperties().setProperty("i", 0);
}

Upvotes: 1

Related Questions