Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a thread to run on specific time in java?

I want o make threads execute at specific exact times (for example at: 2012-07-11 13:12:24 and 2012-07-11 15:23:45)

I checked ScheduledExecutorService, but it only supports executing after specific period from the first run and I don't have any fixed periods, instead I have times from database to execute tasks on.

In a previous question for a different problem here, TimerTask was the solution, but obviuosly I can't make thread a TimerTask as Runnable and TimerTask both have the method run which needs to be implemented. The question here if I make the thread extends TimerTask and have one implementation of run(), would that work? If not, then how it's possible to do what I'm trying to do?

like image 363
Sami Avatar asked Jul 11 '12 12:07

Sami


People also ask

How do you call a specific time in Java?

You can schedule a method at some time using Timer and TimerTask . For example: Calendar calendar = Calendar. getInstance(); calendar.

How do you make a thread wait for some time?

In between, we have also put the main thread to sleep by using TimeUnit. sleep() method. So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution.

Do threads run at the same time Java?

First of all, each thread will consume CPU time to work. Therefore, if our application is running on a computer with a single-core CPU, it's impossible to start two threads at exact same time. If our computer has a multi-core CPU or multiple CPUs, two threads can possibly start at the exact same time.


3 Answers

Use TimerTask .

Create a TimerTask object with a field variable as your thread. Call the Thread start from the Timer task Run method.

public class SampleTask extends TimerTask {
  Thread myThreadObj;
  SampleTask (Thread t){
   this.myThreadObj=t;
  }
  public void run() {
   myThreadObj.start();
  }
}

Configure it like this.

Timer timer  new Timer();
Thread myThread= // Your thread
Calendar date = Calendar.getInstance();
date.set(
  Calendar.DAY_OF_WEEK,
  Calendar.SUNDAY
);
date.set(Calendar.HOUR, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
// Schedule to run every Sunday in midnight
timer.schedule(
  new SampleTask (myThread),
  date.getTime(),
  1000 * 60 * 60 * 24 * 7
);
like image 185
Akhi Avatar answered Oct 21 '22 19:10

Akhi


I think you should better use some library like the Quartz Scheduler. This is basically an implementation of cron for Java.

like image 20
carlspring Avatar answered Oct 21 '22 20:10

carlspring


Have you looked at CountDownLatch from the java.util.concurrent package? It provides a count down then triggers the thread(s) to run. I never needed to use it myself, but have seen it in use a couple times.

like image 2
posdef Avatar answered Oct 21 '22 20:10

posdef