简体   繁体   English

使用计时器安排Java线程

[英]Scheduling Java Threads with timer

I have a Runnable class that needs to run after a set interval since it last ran. 我有一个Runnable类,自上次运行以来,它需要在设置的时间间隔后运行。 Example: ProcessThread runs every 2 mins after it finishes. 示例:ProcessThread完成后每2分钟运行一次。 So if I start ProcessThread at 1:00, and it takes 5 mins (finishing at 1:05), the next time it should run would be at 1:07. 因此,如果我在1:00开始启动ProcessThread,并且花费5分钟(在1:05完成),则下次应在1:07运行。 If that one takes 3 mins to run, (finishing at 1:10), the next one starts at 1:12) and so on.. 如果该程序需要3分钟才能运行(以1:10完成),那么下一个程序将以1:12开始),依此类推。

I can't set it with a Fixed Rate of 2 minutes, because then a second Thread would be fired and the first one hasn't finished yet. 我无法将其设置为2分钟的固定费率,因为这将触发第二个线程,而第一个线程尚未完成。

So, here is my current code, but the way I have it, it keeps creating threads and never finishes them... so eventually my memory grows and grows: 因此,这是我当前的代码,但是按照我的方式,它会不断创建线程,并且永远不会完成线程...因此最终,我的内存会越来越大:

Main: 主要:

public class MyMain extends Thread{
   public static void main(String[] args)  {        

    ExecuteThread execute = new ExecuteThread();
    execute.start();
   }
}

ExecuteThread (I took out the try-catch): ExecuteThread(我取出try-catch):

public void run() {

      MyProcessThread myProcess = new MyProcessThread();
      ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

      myProcess.start();
      while(myProcess.isAlive()){
         sleep(10000);
      }

      scheduler.schedule(this,myProcess.getDelaySeconds(),TimeUnit.SECONDS);

}

Before I had the scheduler run inside the MyProcessThread, but it resulted in the same. 在让调度程序在MyProcessThread内运行之前,但是结果还是一样。 This looks to be the correct direction but something is still wrong. 这似乎是正确的方向,但仍然存在问题。

You can do 你可以做

scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleWithFixedDelay(command, 0, 2, TimeUnit.MINUTES);

That will create a an executor that will run command 2 minutes after the previous command run finishes. 这将创建一个执行程序,该执行程序将在上一个command运行完成后2分钟运行command Check the documentation here . 此处检查文档。

Here's a snippet of it. 这是它的一个片段。

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next . 创建并执行一个周期性操作,该操作将在给定的初始延迟后首先启用, 然后在一个执行的终止与下一个执行的开始之间以给定的延迟启用 If any execution of the task encounters an exception, subsequent executions are suppressed. 如果该任务的任何执行遇到异常,则将禁止后续执行。 Otherwise, the task will only terminate via cancellation or termination of the executor. 否则,任务将仅通过取消或终止执行程序而终止。

Take into account the last sentence about if there's any exception from the command! 请考虑最后一句话,即命令中是否有任何异常!

您可以finally在MyProcessThread中安排下一次执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM