Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run java thread at specific times

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?

like image 926
Ricardo Marimon Avatar asked Mar 13 '10 03:03

Ricardo Marimon


People also ask

How do you run a thread periodically?

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.

How do you start a thread 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.

How do you run the same thread multiple times?

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.


1 Answers

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);
        }
    }
}
like image 156
Enno Shioji Avatar answered Sep 20 '22 16:09

Enno Shioji