java - 如何调用线程在特定时间运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11432498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:06:41  来源:igfitidea点击:

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

javamultithreadingtimertask

提问by Sami

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)

我想让线程在特定的确切时间执行(例如:2012-07-11 13:12:24 和 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.

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

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

在一个不同的问题,前一个问题在这里,TimerTask的是解决方案,但obviuosly我不能让一个线程TimerTask作为RunnableTimerTask两者都有方法run需要被实现。这里的问题是,如果我让线程扩展TimerTask并实现run(),那会起作用吗?如果没有,那么怎么可能做我想做的事情?

回答by Akhi

Use TimerTask .

使用 TimerTask 。

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

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

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
);

回答by carlspring

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

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

回答by posdef

Have you looked at CountDownLatchfrom 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.

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