Add more logging, don't throw exception at timers

This commit is contained in:
Manfred Karrer 2016-02-19 22:21:56 +01:00
parent d506a1acfc
commit 8b1c0e5e6f
9 changed files with 97 additions and 87 deletions

View file

@ -7,9 +7,6 @@ import java.time.Duration;
import java.util.Random;
import java.util.TimerTask;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public class DefaultJavaTimer implements Timer {
private final Logger log = LoggerFactory.getLogger(DefaultJavaTimer.class);
private java.util.Timer timer;
@ -20,46 +17,53 @@ public class DefaultJavaTimer implements Timer {
@Override
public Timer runLater(Duration delay, Runnable runnable) {
checkArgument(timer == null, "runLater or runPeriodically already called on that timer");
timer = new java.util.Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Thread.currentThread().setName("TimerTask-" + new Random().nextInt(10000));
try {
UserThread.execute(runnable::run);
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing timerTask failed. " + t.getMessage());
if (timer != null) {
timer = new java.util.Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Thread.currentThread().setName("TimerTask-" + new Random().nextInt(10000));
try {
UserThread.execute(runnable::run);
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing timerTask failed. " + t.getMessage());
}
}
}
}, delay.toMillis());
}, delay.toMillis());
} else {
log.warn("runLater called on an already running timer.");
}
return this;
}
@Override
public Timer runPeriodically(java.time.Duration interval, Runnable runnable) {
checkArgument(timer == null, "runLater or runPeriodically already called on that timer");
timer = new java.util.Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Thread.currentThread().setName("TimerTask-" + new Random().nextInt(10000));
try {
UserThread.execute(runnable::run);
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing timerTask failed. " + t.getMessage());
if (timer != null) {
timer = new java.util.Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Thread.currentThread().setName("TimerTask-" + new Random().nextInt(10000));
try {
UserThread.execute(runnable::run);
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing timerTask failed. " + t.getMessage());
}
}
}
}, interval.toMillis(), interval.toMillis());
}, interval.toMillis(), interval.toMillis());
} else {
log.warn("runLater called on an already running timer.");
}
return this;
}
@Override
public void stop() {
checkNotNull(timer, "Timer must not be null");
timer.cancel();
timer = null;
if (timer != null) {
timer.cancel();
timer = null;
}
}
}