Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Timer class: timer tasks stop to execute if in one of the tasks exception is thrown

Tags:

java

timer

new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
       System.out.println("run");
       throw new SomeRandomException();
    }
 }, 1000, 1000);

Output: run (exception is thrown)

Here is the problem: I need a timer task to check for specific conditions in the database (or something else). It worked fine, but sometimes the database(or something else) returns some errors, exception is thrown and the timer crashes, and then no single timer task is executed again. Is there a some Timer implementation which keep working after exception is thrown in run().

I can

new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        try {
            System.out.println("run");
            throw new SomeRandomException();
        } catch (Exception e) {
            System.out.println("dummy catch");
        }
    }
}, 1000, 1000);

but this seems lame.

Other alternative is write my own implementation of Timer class, swallowing exceptions of run method (which seems also not right).

like image 332
Kiril Kirilov Avatar asked Jan 05 '12 13:01

Kiril Kirilov


People also ask

How do you stop a Timer in Java?

In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.

Which method of the Timer object will stop a running Timer before it has completed?

Java Timer object can be created to run the associated tasks as a daemon thread. Timer cancel() method is used to terminate the timer and discard any scheduled tasks, however it doesn't interfere with the currently executing task and let it finish.

How does the Timer class work in Java?

Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions.


1 Answers

Use a ScheduledExecutorService. It plays the same role as Timer, but fixes its weaknesses (like the one you're encountering).

like image 51
JB Nizet Avatar answered Oct 04 '22 15:10

JB Nizet