Sending an email every half hour if a certain condition is met This will be called every minute from the background thread. If my unauthorizedCount and badRequestCount 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
    }

    // send an email for bad request count
    if (Integer.parseInt(badRequestCount) != 0) {
        // send an email here
    }       
}


For example, if my unauthorizedCount is non-zero, then it will be non-zero at least for an hour. That means it will keep on sending out an email every minute for an hour, so our email will get flooded up with this. That's what I don't want to have, same thing with badRequestCount.

Now what I want to do is, as soon as unauthorizedCount is non-zero, it will send out its first email. If it is non-zero again continuously for half an hour, then I would like to send another email after half an hour. If it is non-zero continuously, but suppose if the first time it was non-zero, I will send out an email. Next time it is non-zero, I won't send another email, but if the third time it was zero, then I will reset the counter so that it sends out an email instantly.

I basically 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.

private static long lastUnauthorizedSent = -1;
private static long lastBadRequestSent = -1;

private void callMetrics() {

    // .. some other code

    long now = new Date().getTime();

    // send an email for unauthorized count     
    if (Integer.parseInt(unauthorizedCount) != 0 &amp;&amp; satisfiesUnauthorizedSinceLast(now)) {
        // send an email here
        lastUnauthorizedSent = now;
    } else {
        lastUnauthorizedSent = -1;
    }

    // send an email for bad request count
    if (Integer.parseInt(badRequestCount) != 0 &amp;&amp; satisfiesBadRequestSinceLast(now)) {
        // send an email here
        lastBadRequestSent = now;
    } else {
        lastBadRequestSent = -1;
    }       
}

private void satisfiesUnauthorizedSinceLast(long now) {
    return lastUnauthorizedSent == -1 || now - lastUnauthorizedSent &gt; 30*60*1000;
}

private void satisfiesBadRequestSinceLast(long now) {
    return lastBadRequestSent == -1 || now - lastBadRequestSent &gt; 30*60*1000;
}
We know what this is 30*60*1000 but you should put that into a variable instead of just letting it lay around out there naked like that.

public long waitTime = 30*60*1000;


and you can put it in whatever scope that you want to and use it as often as you like, just make sure that if you change it you know what it will affect.