需要在java中以固定的持续时间重复执行一段代码

需要在java中以固定的持续时间重复执行一段代码,java,multithreading,java.util.concurrent,Java,Multithreading,Java.util.concurrent,我已经写了一段代码。如何让代码重复运行一定的时间,比如10秒?似乎提供了一些方法,可以执行任务,直到任务完成,或者出现超时,例如。您可以尝试 Quartz是一个功能丰富的开源作业调度库 可以集成到几乎任何Java应用程序中—从 最大电子商务系统的最小独立应用程序。 Quartz可用于创建简单或复杂的执行计划 数十个、数百个甚至数万个工作岗位;任务是什么的工作 定义为可以虚拟执行的标准Java组件 你可以让他们做任何事。石英调度器包括 许多企业级功能,例如对JTA事务的支持 和聚类 如果您熟悉Li

我已经写了一段代码。如何让代码重复运行一定的时间,比如10秒?

似乎提供了一些方法,可以执行任务,直到任务完成,或者出现超时,例如。

您可以尝试

Quartz是一个功能丰富的开源作业调度库 可以集成到几乎任何Java应用程序中—从 最大电子商务系统的最小独立应用程序。 Quartz可用于创建简单或复杂的执行计划 数十个、数百个甚至数万个工作岗位;任务是什么的工作 定义为可以虚拟执行的标准Java组件 你可以让他们做任何事。石英调度器包括 许多企业级功能,例如对JTA事务的支持 和聚类


如果您熟悉Linux,这对您来说将是一个艰难的过程。

使用辅助线程并在线程中启动它,在主线程中等待特定时间,然后停止辅助线程

MyRunnable task = new MyRunnable();
Thread worker = new Thread(task);
// Start the thread, never call method run() direct
worker.start();

Thread.sleep(10*1000); //sleep 10s
if (worker.isAlive()) {
    task.stopPlease(); //this method you have to implement 
}

不太清楚为什么人们对这个问题投了反对票。以后一定要提供一些示例代码。然而,你的答案在这里很简单。创建一个新线程来观察等待。在简单代码中:

public class RunningClass {
     public static void runThis(){
          TimerThread tt = new TimerThread();
          tt.timeToWait = 10000;
          new Thread(tt).start();
          while (!TimerThread.isTimeOver){
                \\Code to execute for time period
          }
 }

 class TimerThread implements Runnable {

      int timeToWait = 0;
      boolean isTimeOver = false;

       @override
       public void run(){
            Thread.sleep(timeToWait);
       }
  }
上面的代码可以放在同一个类文件中。将10000更改为您需要它运行的任何时间


您可以使用其他选项,但这需要您了解员工和任务。

不确定确切要求是什么,但 如果您的请求仅取消长时间运行的任务

您可以在JDK5中使用ExecutorService&Future,如下所示

ExecutorService fxdThrdPl=Executors.newFixedThreadPool2

    // actual task .. which just prints hi but after 100 mins
    Callable<String> longRunningTask = new Callable<String>() {
        @Override
        public String call() throws Exception {
            try{
                TimeUnit.MINUTES.sleep(100); // long running task .......   
            }catch(InterruptedException ie){
                System.out.println("Thread interrupted");
                return "";                          
            }               
            return "hii"; // result after the long running task
        }
    };

    Future<String> taskResult = fxdThrdPl.submit(longRunningTask); // submitting the task
    try {

        String output = taskResult.get(***10**strong text**, TimeUnit.SECONDS***);
        System.out.println(output);
    } catch (InterruptedException e) {          
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
        ***taskResult.cancel(true);***
    }