本文介绍了如何调用线程在java中的特定时间运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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.

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

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?

推荐答案

使用TimerTask。

Use TimerTask .

用字段创建TimerTask对象变量作为你的线程。
从Timer任务Run方法调用Thread启动。

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

像这样配置。

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

这篇关于如何调用线程在java中的特定时间运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 04:13