Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reschedule a task using timer?

Here is my problem, I am sending some message to a queue using JMS. The program has been written in such a way that there will be a message sent to the queue within 30 seconds from the time of the previous message sent. If there are no messages sent in the 30 seconds duration then the message is the last message and I should start consuming the messages from the queue.

My Initial thought is to create a timer with a task(Here receiving message form the queue), when a new message is created, the method is called and the task waits for 30sec. If the method is called again that means another message has come so the task has to be rescheduled.

This is the code I have written:

public void startTimer() {
    Timer t = new Timer();
    try {
        t.schedule(task, timeDelay);
    } catch (Exception e) {
        t.cancel();
        t = new Timer();
        t.schedule(task, timeDelay);
    }
}

I am trying to schedule a timer, if there is an existing task scheduled to it then I am canceling that timer, creating a new timer and scheduling a new task.

I am getting error message as Task already scheduled or cancelled.

Any idea for improvement or suggestions or solutions are most welcome.

like image 291
NewUser Avatar asked Nov 27 '13 12:11

NewUser


People also ask

How do you schedule a Timer in Java?

Java Timer schedule() methodThe schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.

What is a Timer task?

A task that can be scheduled for one-time or repeated execution by a Timer.

How do you end a Timer task?

The cancel() method is used to cancel the timer task. The cancel() methods returns true when the task is scheduled for one-time execution and has not executed until now and returns false when the task was scheduled for one-time execution and has been executed already.

What is Timer delay Java?

Timers are constructed by specifying both a delay parameter and an ActionListener . The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds. Once the timer has been started, it waits for the initial delay before firing its first ActionEvent to registered listeners.


1 Answers

You cannot use the same TimerTask in one or several Timer.

You need to create a new instance of the TimerTask to be executed:

t.cancel();
t = new Timer();
TimerTask newTask = new MyTimerTask();  // new instance
t.schedule(newTask, timeDelay);
like image 88
Jean Logeart Avatar answered Sep 17 '22 12:09

Jean Logeart