Pale Dot
Pale Dot

Reputation: 17

Call method once every 5 minutes

I want to send 1 mail every 5 minutes irrepective of how many times i call sendmail() in 5 minutes ? For eg.

How to achieve it?

public class SendMyEmail {
 private boolean sendMail=false;
 public void sendmail(String msg) {
 if(sendMail) {
 System.out.println(" Mail sent " +msg);
 }

Upvotes: 1

Views: 1543

Answers (4)

Valerij Dobler
Valerij Dobler

Reputation: 2764

What you have is almost what you need. The cron expression means, trigger every 5 minutes: on Minute 0, 5, 10, etc.

public class SendMyEmail
{
    private volatile String mailMessage;

    public void sendmail(String msg)
    {
        mailMessage = msg;
    }

    @Scheduled(cron = "*/5 * * * *")
    public void sendmailJob()
    {
        if (mailMessage != null)
        {
            System.out.println(" Mail sent " + mailMessage);
            mailMessage = null;
        }
    }
}

Upvotes: 0

Guilherme Barboza
Guilherme Barboza

Reputation: 652

You'll have to create what we call a Schedule - a procedure that runs consistently and periodically. Your Schedule would have the following logic:

@Scheduled(cron = "0 * * * * *") // Will run every minute
public synchronized void sendEmailSchedule() {

    Email email = getEmail();

    Date lastTimeSent = email.getLastTimeEmailWasSent();
    Date now = new Date();
    
    long difference = now.getTime() - lastTimeSent.getTime();
    long differenceInMinutes = difference / (60 * 1000) % 60; 
    
    if (differenceInMinutes > 5) {
        sendEmail(email);
    }
}

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

You could simply create a timestamp when your class is instantiated (in the constructor).

Your send method simply checks "more than 5 minutes since that timestamp"?

If yes: then take a new timestamp, and send the mail.

If no: do nothing.

That's all you will need. Not going to provide code here, as this is probably homework, and the point is that you learn how to write the corresponding code.

Upvotes: 2

Manan Adhvaryu
Manan Adhvaryu

Reputation: 333

Have a variable in your SendMyEmail class that stores the time when you call your function. Then simply add your logic to an if condition that checks if it has been 5 minutes since the method was called.

Upvotes: 2

Related Questions