How to retain value of a variable across different runs

1,269 views
Skip to first unread message

Margah GNITS

unread,
May 25, 2022, 7:54:24 PM5/25/22
to Google Apps Script Community
Hello

I am running a program to compare values in two different sheets.  The function is trigerred every minute.  What i want is for some statements to execute the first time the comparision results evaluate to true.  After that it should not execute the statements.  

I have declared a global variable and initialized it to 0.  When the condition evaluates to true the first time I am setting the global variable to 1.  I am resetting it to 0 later in else block.  The problem is everytime the function is trigerred the variable is getting initialized to 0.  It is not retaining the value of 1 which I assigned in the previous run.  Is there an alternate way I can do this. 

Attaching a snippet of the relevant code.  Please ignore syntax errors if any.

//Global variable 
mail_trigerred = 0;

send_email()   //Trigerred every minute
{
//other lines of code are here.   
if (last_value_h.join() == last_value_u.join())
  {
         if (mail_triggered == 0)
        {
        Logger.log(mail_triggered);
        var emailAddress2= 'x...@gmail.com';
        var message= 'Hello';
        var subject = 'Not working';
        MailApp.sendEmail(emailAddress2,subject,message);
        mail_triggered = 1;
        }                
  }
  else
  {
      mail_triggered = 0;
      archive();
   } 
}
  

Clark Lind

unread,
May 26, 2022, 6:52:58 AM5/26/22
to Google Apps Script Community
Hello, you should be able to persist values using the propertiesService.  

Something like this (untested, but the concept). Since it uses strings for the values, I changed the 0 and 1 to false and true respectively.

//Global variable
//mail_trigerred = 0;
var scriptProperties = PropertiesService.getScriptProperties();
var mail_trigerred = scriptProperties.getProperty('mail_trigerred')


send_email()   //Trigerred every minute
{
//other lines of code are here.  
if (last_value_h.join() == last_value_u.join())
  {
         if (mail_triggered == 'false' || mail_trigerred == null)   //the very first run should be null until the value is set

        {
        Logger.log(mail_triggered);
        var emailAddress2= 'x...@gmail.com';
        var message= 'Hello';
        var subject = 'Not working';
        MailApp.sendEmail(emailAddress2,subject,message);
        scriptProperties.setProperty( 'mail_trigerred', 'true' );
        }                
  }
  else
  {
      scriptProperties.setProperty( 'mail_trigerred', 'false');
      archive();
   }
}

Margah GNITS

unread,
May 26, 2022, 10:53:06 AM5/26/22
to Google Apps Script Community
Thank you very much buddy.  That worked for me.  
Reply all
Reply to author
Forward
0 new messages