john
john

Reputation: 11709

How to send an email every half an hour if certain condition is met during that period?

I have my below method which will be called every one minute from the background thread.

In my below code, if my unauthorizedCount is not equal to zero, then I send out an email.

private void callMetrics() {

    // .. some other code

    // send an email for unauthorized count
    if (Integer.parseInt(unauthorizedCount) != 0) {
        // send an email here
    }
}

Now if my unauthorizedCount is non zero, then it will be non zero atleast for an hour so it means, it will keep on sending out an email every 1 minute for an hour so our email will get flooded up with thiis email and that's what I don't want.

Now what I want to do is - as soon as unauthorizedCount is non zero, then it will send out its first email but then I doon't want to send another email in next minute as my background thread runs every 1 minute, I would like to send it out after half an hour again. So basically I want to send out my first email whenever unauthorizedCount is non zero but if it is non zero again in the next minute, then I don't want to send out another email and will send out another email if unauthorizedCount is non zero after half an hour.

How can I accomplish this? Should I use some multiplier here?

Upvotes: 0

Views: 1615

Answers (2)

Zeshan Khan
Zeshan Khan

Reputation: 294

You may use other variables like email_sent,mail_at and set it true in the email send code and the time_at = the current time. Then before sending an email check two things the email_sent and the date time (mail_at) if email_sent is false or the current time - time_at is half hour then send the email. Here is the code that is not written in a specified language or development technology but you may easily convert into your required language.

`
method()
{
    time_at=Time.Now();
    email_sent=false;
    if(time or event occurs)
    {
        if(!email_sent&&Time.Now-time_at>30*60*1000)//milisecond
        {
            email_sent=true;time_at=Time.Now;
            send_emai();//this is the actual mail sending method
        }
    }
}
`

Upvotes: 1

Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

private void callMetrics() {

    // .. some other code

    // send an email for unauthorized count
    long now = new Date().getTime();
    if (Integer.parseInt(unauthorizedCount) != 0 && satisfiesSinceLast(now)) {
        // send an email here
        lastSent = now;
    }
}

private void satisfiesSinceLast(long now) {
    return lastSent == -1 || now - lastSent > 30*60*1000;
}

Keep lastSent as a member of that class, initialize with -1 (nothing was sent at the beginning) and update on each send. Then when you check your condition check if it's been 30 minutes (30*60*1000) since your last email.

Upvotes: 1

Related Questions