Evilsithgirl
Evilsithgirl

Reputation: 329

Java Time Delay

I am having trouble with the following bit of code.

//Send Creation email
ListServDAO.sendCreateEmail(orgId, full, request.getSession().getServletContext());
//Force a 1 minute pause
       Timer timer = new Timer();
       timer.schedule(new TimerTask() {
            public void run() {
                //Send add members email
                ListServDAO.sendAddMembersEmail(orgId, request.getSession().getServletContext());
                }
            }, 0, 60 * 1000);

The sendAddMembersEmail function does not wait 1 minute to send after the sendCreateEmail function call. I am not sure why it is not waiting even after reading the java API. I do not wish to use the Thread.sleep method because I want the user to be able to use the application while waiting for the emails to send.

Upvotes: 0

Views: 2703

Answers (4)

mprabhat
mprabhat

Reputation: 20323

2nd parameter is the initial delay which you are passing as 0 hence it it executing it right then and there, pass 60000 second for it to wait for a minute and then send.

Since you just want it to send only once use, call Timer.schedule(TimerTask task, long delay)

Off-topic:

You should consider using ScheduledExecutorService instead of Timer. See Oracle Tutorial.

Upvotes: 2

Jim Barrows
Jim Barrows

Reputation: 3634

You have the order of the params wrong:

    schedule(TimerTask task, long delay, long period) 
      Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.

Swap the 0 and 60*1000.

Upvotes: 1

Krrose27
Krrose27

Reputation: 1036

You have an extra zero.

What you are calling is Delayed with a Fixed-Delay Repeat Execution and what you want is a Single Delay Non Repeat execution.

Upvotes: 1

jtahlborn
jtahlborn

Reputation: 53694

are you intending to repeatedly send emails? if not, why are you using the method which takes 2 longs (i.e. "repeatedly run this task every <period> milliseconds")? use the schedule(task, delay) method (and use a non-zero delay).

Upvotes: 2

Related Questions