What is the best way to create a background thread that will run every 15 minutes to get the data from the database?
Below is the code I have which will work fine I guess in production but is there any other way better that I have or something that I should be aware of?
private static void checkDatabaseEveryXMinutes() {
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(checkingAfterEveryXMinutes);
getDataFromDatabase();
} catch (InterruptedException ex) {
//log here
} catch (Exception e) {
//log here
}
}
}
}.start();
}
Is there any disadvantage in using the above code. And how does ScheduledExecutorService compares with TimerTask?
Which way is better?
Any example basis on my code will be appreciated on this if there are any better approach.
ScheduledExecutorService
, you simplyscheduleAtFixedRate
(orscheduleWithFixedDelay
), and everything is automatically taken care of. – Zoolatry