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).
In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.
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.
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.
Use a ScheduledExecutorService
. It plays the same role as Timer, but fixes its weaknesses (like the one you're encountering).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With