I have a web application that synchronizes with a central database four times per hour. The process usually takes 2 minutes. I would like to run this process as a thread at X:55, X:10, X:25, and X:40 so that the users knows that at X:00, X:15, X:30, and X:45 they have a clean copy of the database. It is just about managing expectations. I have gone through the executor in java.util.concurrent
but the scheduling is done with the scheduleAtFixedRate
which I believe provides no guarantee about when this is actually run in terms of the hours. I could use a first delay to launch the Runnable
so that the first one is close to the launch time and schedule for every 15 minutes but it seems that this would probably diverge in time. Is there an easier way to schedule the thread to run 5 minutes before every quarter hour?
The best way to do this thing is to use AlarmManager class. 2) set Broadcast receiver in Alarmmanager, it will call Receiver every particular time duration, now from Receiver you can start your thread . if you use Timer task and other scheduler, Android will kill them after some time.
To do this properly, you need to use a ScheduledThreadPoolExecutor and use the function schedule like this: final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS); executor. schedule(new Runnable() { @Override public void run() { captureCDRProcess(); } }, 1, TimeUnit.
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
You can let the Runnable schedule its "next run".
Such as,
class Task implements Runnable {
private final ScheduledExecutorService service;
public Task(ScheduledExecutorService service){
this.service = service;
}
public void run(){
try{
//do stuff
}finally{
//Prevent this task from stalling due to RuntimeExceptions.
long untilNextInvocation = //calculate how many ms to next launch
service.schedule(new Task(service),untilNextInvocation,TimeUnit.MILLISECONDS);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With