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 will return you a Future that has an additional method to check if the Runnable completed. Both have methods for canceling the Runnable. For repeated task like this, checking if it's done, is probably not going to be of much use. However, it was introduced with jdk 1.5 concurrency api, which should definitely be used in place of older concurrency/thread api's (Timer and TimerTask were jdk 1.3). They will be more robust, and better performant. They have a very similar example as your use case in the java doc here.
here's a sample:
tieTYT is right. If you are using it in an application server, you can use the ejbtimer service of the specific server
You can try using java.util.TimerTask and java.util.Timer
Example is here:-