Google Scripts: How to call a function to run after another function is completed

前端 未结 1 1224
予麋鹿
予麋鹿 2021-01-28 13:55

I have a google script with 4 different functions that need to run one after another, but a function can run just after the previous one has finished/completed.

The tim

相关标签:
1条回答
  • 2021-01-28 14:15

    In the general case, to run function A after function B, one writes a controller routine that first calls one, then calls the other:

    function a() { /* stuff */ }
    function b() { /* other stuff */ }
    function doStuff() {
      a();
      b();
    }
    

    For your case, where you have an execution time limit to deal with that would otherwise kill they execution of one of your functions and prevent the rest from running, you need to write a scheduling routine that makes use of Apps Scripts ScriptApp class. You have a number of ways to do this, from scheduling the first with a set interval trigger and using each function to tell Google when to run the next function, rather than to run the next function, or using a script property to indicate the next function which be run, to manually running one and having the last one set up a call for the first.

    Example of chaining:

    function a() {
      ...
      // Google will run b() within +/-15 minutes of the indicated time
      // Schedule it for 16 minutes from now, so we know a() has
      // completed and shut down before b runs.
      var next = ScriptApp.newTrigger("b").timeBased();
      next.after(16 * 60 * 1000).create();
    }
    function b(e) {
      /* Add code to delete the one-time trigger used to call this function
      (The trigger uid is in the event object e) */
      ...
    

    Property method:

    function doStuff() {
      var props = PropertiesService().getScriptProperties();
      var next;
      switch (props.getProperty("runNext")) {
        case "a":
          a();
          next = "b";
          break;
        ...
      }
      props.setProperty("runNext", next);
    }
    function a() {...}
    ...
    

    If you implement a solution that chains functions (vs. one that uses a property to indicate which to run), you will want to make sure you delete previous triggers to prevent the trigger count from growing endlessly.

    0 讨论(0)
提交回复
热议问题