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

前端 未结 3 1881
天命终不由人
天命终不由人 2021-02-05 18:54

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

相关标签:
3条回答
  • 2021-02-05 19:10

    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.

    0 讨论(0)
  • 2021-02-05 19:11

    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
    );
    
    0 讨论(0)
  • 2021-02-05 19:20

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

    0 讨论(0)
提交回复
热议问题