Check if Trigger is already running

Viewed 34

I'm trying to run a script on a Google Sheet that updates the sheets after pulling data from a MySQL DB. It runs a trigger at the end, but I think it's re-starting the trigger every time it runs, resulting in multiple timeBased triggers running concurrently. I don't know Java, but is there a way to check if the trigger is already running and bypass if it is?

Like:

if (trigger_running) {continue} else {runTrigger}?

Here's the basics of the function & trigger:

function readData() {
  //open connection
  //fetch data
  //update sheet(s)
  //close connection
}


/* Schedule run/update */
 ScriptApp.newTrigger('readData')
 .timeBased()
 .everyMinutes(5)
 .create();
2 Answers

Your ScriptApp.newTrigger() call is in the global space which makes it run every time any function in your script project gets executed. You should delete that bit of code or comment it out.

Then visit the My Triggers dashboard and delete the myriad triggers that have been created this far. Finally, open your script project and manually create one trigger to run the readData() function. See installable triggers.

A trigger test

function clockMe(e) {
  if (e) {
    Logger.log(JSON.stringify(e));
    const ss = SpreadsheetApp.getActive();
    const sh = ss.getSheetByName("Sheet0");
    const lr = sh.getLastRow();
    if(lr > 0) {
      sh.getRange(lr + 1,1).setValue(new Date()).setNumberFormat("HH:mm:ss")
    } else {
      sh.getRange(1,1).setValue(new Date()).setNumberFormat("HH:mm:ss")
    }
  }
}

function createTrigger() {
  if (ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "clockMe").length == 0) {
    ScriptApp.newTrigger("clockMe").timeBased().everyMinutes(1).create();
  }
}

function removeTrigger() {
  ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "clockMe").forEach((t => ScriptApp.deleteTrigger(t)))
}

Sheet:

enter image description here

You can also watch the triggers from here:

enter image description here

Related