I'm currently working on a project that logs data from a website to a database every x hours.
But when the database connection properties are not good, the program does not throw a RuntimeException
pretends everything is fine.
When the schedule has a RuntimeException
(configuration or connection to database exceptions), I have to stop the whole program and tell the user about the exception.
private static ScheduledExecutorService executeWithPeriod(Runnable runnable, int period) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, Math.max(1, period), TimeUnit.HOURS);
return executor;
}
The runnable
takes care of getting data and saving it to the database.
RuntimeException
:All these exceptions extends RuntimeException
Someone have the solution to throws the RuntimeException
to the main thread ?
You haven't demonstrated a need for multiple threads, so you can eliminate the complexity of signaling between concurrent threads. Use a single thread instead:
final class YourTask {
public static void main(String... args) throws InterruptedException {
YourTask task = new YourTask();
while (true) {
try {
task.doYourThing();
} catch (Exception ex) {
ex.printStackTrace();
break;
}
TimeUnit.HOURS.sleep(1L);
}
}
private void doYourThing() throws Exception {
System.out.println("I'm saving data from a website to a database!");
throw new RuntimeException("Oh no! I can't read my configuration!");
}
}
Note that this solution "tells the user about the problem" and "stops the whole program," as specified.