12

我想让线程在特定的确切时间执行(例如:2012-07-11 13:12:24 和 2012-07-11 15:23:45)

我检查了ScheduledExecutorService,但它只支持在第一次运行的特定时间段后执行,而且我没有任何固定的时间段,而是我有时间从数据库执行任务。

在上一个针对不同问题的问题中 TimerTask 是解决方案,但显然我不能将线程 aTimerTask作为Runnable并且TimerTask两者都有run需要实现的方法。这里的问题是,如果我使线程扩展TimerTask并具有一个实现run(),那会起作用吗?如果没有,那么怎么可能做我想做的事?

4

3 回答 3

17

使用 TimerTask 。

创建一个带有字段变量的 TimerTask 对象作为您的线程。从 Timer 任务的 Run 方法调用 Thread start。

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

像这样配置它。

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
);
于 2012-07-11T12:59:52.383 回答
4

我认为你应该更好地使用像Quartz Scheduler这样的库。这基本上是 Java 的 cron 实现。

于 2012-07-11T12:26:00.003 回答
2

你看过java.util.concurrent 包中的CountDownLatch吗?它提供倒计时然后触发线程运行。我从来不需要自己使用它,但已经看过几次了。

于 2012-07-11T12:28:04.600 回答