adi
adi

Reputation: 1741

How to call a method after some specific interval of time in Java

Here is the use case:

I am using Java (with Spring)

Once the user (through a web-app) confirms to the subscription, I want to send him an email exactly after 30 mins.

Now how to do this? Do I need a message broker? or something like ScheduledExecutorService? Do I need some sort of queue?

Please advise.

Upvotes: 4

Views: 5227

Answers (4)

Muhammed Fasil
Muhammed Fasil

Reputation: 8576

Create an object for Timer

 private Timer myTimer;

in main method

myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
           //your method
        }

    }, 0, 200);

Upvotes: 2

Partha
Partha

Reputation: 570

It is not that the thread will die after sending the mail. When you configure Quartz, a new thread will automatically be created and will execute the assigned task on specified interval. Or else you use Timer class also. It is very easy to use.

    Timer timer = new Timer(); // Get timer

    long delay = 30 * 60 * 1000; // 3o min delay

    // Schedule the two timers to run with different delays.
    timer.schedule(new MyTask(), 0, delay);

...................



class MyTask extends TimerTask {

    public void run() {
        // business logic
        // send mail here
    }
}

Upvotes: 0

RMT
RMT

Reputation: 7070

You can use the Quartz Scheduler. Its fairly easy to use. You can schedule something every week or ever 30 minutes or whatever you want basically.

Upvotes: 2

Nishant
Nishant

Reputation: 55886

Can look into quartz scheduler for this.

By the way a common strategy is to send a bulk of all pending mails in bulk in every 30 minutes or so. Quartz can help in do that as well.

Upvotes: 4

Related Questions