google-sheetsgoogle-apps-scripttriggersadd-on

Time-Driven Triggers are not triggering as getActiveUser only working on owned by


I have cron_fetchrootservice function and created time-driven trigger manually. Its trigger and data also storing getUserProperties.

But my request is need to run cron_fetchrootservice and save data into the store on behalf of all installed users every 10(some time interval 5 or 10 or 1day) hours. Its not coming and working for other users.

Because this data unique based on each add on installed users.

Otherwise, Need to create dynamic cron job (triggers) for each users while installing time of add-on.

Is it possible to do?

enter image description here

function cron_fetchrootservice() {

   let ActiveUserEmail = Session.getActiveUser().getEmail();
   const storeusers = PropertiesService.getUserProperties();

   // Based on ActiveUserEmail Fetch API call is here return (data).

   storeusers.setProperty("ActiveUser", JSON.stringify(ActiveUserEmail));
   storeusers.setProperty("rootservice_data", JSON.stringify(data));
}

enter image description here


Solution

  • You're saying that you created a trigger manually. An installable trigger runs under the account that created the trigger. Session.getActiveUser() will get that user's identity, and PropertiesService.getUserProperties() will get that users properties, regardless of who the user at the keyboard is. In fact, there may be nobody who has the spreadsheet open at the time the trigger runs.

    You're also referring to "each add on installed users". That would imply that you've deployed the script project as an add-on, but the trigger you created manually will not run in the context of the add-on. It runs in the context of the original script project, which is not the same thing. You could create triggers per user programmatically, but that may not be the best way to structure the process.

    You may instead want to add a list of users in the script's properties, iterate that list, and fetch data from the spreadsheet using each of those user IDs in turn, instead of putting a user IDs in a property as some sort of global flag.

    See JSON.stringify() and JSON.parse() to learn how to encode an array into a string that can be put in properties, and Array.forEach() to learn how to iterate an array, executing a function for each item in the array.

    Also see Triggers for Editor Add-ons and Which user account’s authorizations are used.