I am working on a java web service that is currently connected to a database. Does anyone have an idea how I may query the database every 5 minutes to check for any updates? Any code/information would be greatly appreciated. Thanks!
Asked
Active
Viewed 4,498 times
-3
-
3what are you trying to achieve? It sounds quite vague IMHO – Daan Timmer Feb 27 '12 at 18:33
-
I just want to constantly check for any updates in the database, in order to synchronize the updated information with a mobile device – progdoc Feb 27 '12 at 18:37
-
please excuse me if the question was vague, i'm a newbie hehe ;) – progdoc Feb 27 '12 at 18:38
-
How do you plan to send said information to your device? You state it is a webservice. Thus it relies on a request made. Or you can choose to keep the connection pipe open, but I doubt you do that? – Daan Timmer Feb 27 '12 at 18:40
-
no in this case, my connection pipe will remain open – progdoc Feb 27 '12 at 18:42
-
In that case I suppose @ebaxt his answer should be the correct way :-) (Else I had suggest altering your front-end to do a request every 5minutes) – Daan Timmer Feb 27 '12 at 18:44
-
thank you, I'm trying out different approaches to evaluate which is best( my next approach is altering the front end :D ) – progdoc Feb 27 '12 at 18:45
5 Answers
3
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleWithFixedDelay(new Runnable() {
public void run() {
//put query logic here
}
}
}, 10, 5, TimeUnit.MINUTES);

ebaxt
- 8,287
- 1
- 34
- 36
1
If you are spring framework, there is a library for it. Use
@Scheduled(cron = " * 5 * * * * ")
public void methodName() {
.........
}
Each star represents second, minute, hour, day, month, weekday.
Example patterns:
"0 0 * * * *" = the top of every hour of every day.
"*/10 * * * * *" = every ten seconds.
"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
"0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.
"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
"0 0 0 25 12 ?" = every Christmas Day at midnight

sho fm
- 11
- 2
-1
Sound like you need to create a new Thread, or new Runnable, and just execute your code, and sleep(5000*60);

Churk
- 4,556
- 5
- 22
- 37
-1
If you want this polling to be a constantly running task which runs at a finite interval, then you could probably use the Java TimerTask. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/TimerTask.html

Coolpal
- 11
- 1
-1
-
1) Should use `Executors` instead of `Timers` and 2) Always link most recent javadoc. – mre Feb 27 '12 at 18:39
-
Timers vs. Executors: http://stackoverflow.com/questions/409932/java-timer-vs-executorservice – ebaxt Feb 27 '12 at 18:39