Search code examples
google-apps-scriptgoogle-sheets

GAS passing variables to time based triggers


I have a Google spreadsheet with an onEdit() trigger to create a second time based trigger.

Simply: when the status column is edited to 'Approved' a trigger is created to send a feedback email on a supplied project completion date.

var oneTimeOnly = ScriptApp.newTrigger("emailFeedback").timeBased().at(endDate).create();

I wish to pass a variable to the second trigger. I could create Project Property or add a column in the spreadsheet. However it would be simpler to pass the variable when creating the trigger.

When I insert any additional characters inside the newTrigger quotes this causes the entire contents of the function to be stored in the trigger (which subsequently fails).

var oneTimeOnly = ScriptApp.newTrigger("emailFeedback<strong>(regEmail)</strong>").timeBased().at(endDate).create();

.

Is there a way to store a variable inside the trigger?


Solution

  • Using ScriptDB and new Function(), I was able to create a method for creating dynamic trigger functions.

    The gist of the solution is to store the code you want to trigger is the db with the parameters you want to pass:

    "myFunction('Hello world')"
    

    Then, when the script starts, as a global variable, you attach newly created functions from your ScriptDB. (I've done this dynamically in my link below.)

    globalFunctions.callThisOne = new Function("e", "myFunction("Hello world"));
    

    Finally, when you create your trigger, you created it using the globally accessible function as such:

    ScriptApp.newTrigger("globalFunctions.callThisOne").timeBased().everyDay(1).create();
    

    I have written up a short post about this and posted the source. Hopefully it's useful.

    You can see the code here: https://script.google.com/u/1/home/projects/1bRAoEwswyaZT0TWtu-yl25ixaDQ3sxTaTyp-_3VoF1ubyH0GfZaG5tS4/edit?pli=1