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();
}
1
solved insert data into database after an interval by Java [closed]