I need to build a program in java which will insert a data into mysql database after every 10 min.And this will continue as long as the user terminates the program. Do I need Thread to build the program? Please suggest references or a block of code that will invoke automatically after every 10 min.
Asked
Active
Viewed 774 times
-8
-
1Use a `ScheduledThreadPoolExecutor`. – Sotirios Delimanolis Sep 13 '13 at 18:31
-
@javalover even though your question was put on hold, you can still accept an answer and/or upvote responses :) – SnakeDoc Sep 13 '13 at 20:39
2 Answers
0
You may use the Timer Task for achieving it.
A task that can be scheduled for one-time or repeated execution by a Timer.

Rahul Tripathi
- 168,305
- 31
- 280
- 331
0
I would use the java.util.concurrent.*
package since it's newer and better for threading (which all timers/delay's will need to implement in order to not block your program)
This example will execute your task, then re-schedule itself automatically... nice! (the try/finally block ensures no exception will break our schedule):
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class Task implements Runnable {
long untilNextInvocation = 60000; // 1 minute == 60000 milliseconds
private final ScheduledExecutorService service;
public Task(ScheduledExecutorService service) {
this.service = service;
}
@Override
public void run() {
try {
// do your stuff here
} finally {
service.schedule(new Task(service), untilNextInvocation, TimeUnit.MILLISECONDS);
}
}
}
UPDATE --
How to invoke:
public static void main(String[] args) {
// set 3 available threads
ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
// kick off service
new Task(service).run();
}
OR
You can invoke it from object constructor:
public someClassConstructor() {
// set 3 available threads
ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
// kick off service
new Task(service).run();
}

SnakeDoc
- 13,611
- 17
- 65
- 97
-
That's the basic class I guess, how do I implement in on main as to call this constructor we need a ScheduledExecutorService type object. – Faysal Ahmed Sep 13 '13 at 19:28