简体   繁体   中英

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.

  • if i call sendmail at 10 pm.first mail should be sent
  • If i call sendmail at 10:03 and 10:04 no mail should be sent.
  • If i call sendmail at 10:06 mail should be sent as difference is
    greater than 5 mins

How to achieve it?

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

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.

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.

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);
    }
}

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM