2013-05-08 68 views
0

所以我想用Timer和TimerTask类尝试一下。让程序运行5分钟

我可以在30秒后得到一行代码执行。 我一直在尝试做的是让这行代码执行5分钟。

这是我最初试图

public static void main(String[] args) 
{ 
    for (int i = 0; i <= 10; i ++) 
    { 
     Timer timer = new Timer(); 
     timer.schedule(new TimerTask() 
     { 
      public void run() 
      { 
       System.out.println("30 Seconds Later"); 
      } 
     }, 30000 
     ); 
    } 
} 

我用在for循环的10号,看是否timer.schedule将在循环的下一次迭代中等待下一个30秒。

任何想法我应该怎么做呢?我试着用一个参数传入的时间表方法使用schedule方法,但是这只是让它重新执行,并且它永远不会停止。

+0

可以[这](http://stackoverflow.com/questions/6181420/in-java-is-it-possible-to-execute-a - 方法 - 一段时间后停止)帮助? – Mateusz 2013-05-08 16:20:00

回答

1

你正在运行到的问题是,在不同的线程调度的Timer运行 - 这是,您的for循环的下一次迭代在调度后立即开始运行,而不是在30秒后开始运行。它看起来像你的代码一次启动了10个定时器,这意味着它们应该在30秒后大致打印一次。

当您尝试使用schedule(带有第三个参数)的重复版本时,您处于正确的轨道上。正如你所说,这不是你想要的,因为它无限期地运行。然而,Timer确实有一个cancel方法来防止后续执行。

所以,你应该尝试类似:

final Timer timer = new Timer(); 
// Note that timer has been declared final, to allow use in anon. class below 
timer.schedule(new TimerTask() 
{ 
    private int i = 10; 
    public void run() 
    { 
     System.out.println("30 Seconds Later"); 
     if (--i < 1) timer.cancel(); // Count down ten times, then cancel 
    } 
}, 30000, 30000 //Note the second argument for repetition 
); 
+0

完美的工作,谢谢=) – Shaun 2013-05-08 19:17:59

0

这里有一个解决方法我很惭愧呈现:

package test; 

import java.util.Date; 
import java.util.Timer; 
import java.util.TimerTask; 

public class FiveMinutes { 

    private static int count = 0; 
    // main method just to add example 
    public static void main(String[] args) { 

     Timer timer = new Timer(); 
     timer.schedule(new TimerTask() { 

      @Override 
      public void run() { 
       System.out.println("Count is: " + count); 
       if (count == 1) { 
        System.err.println("... quitting"); 
        System.exit(0); 
       } 
       count++; 
      } 
     }, 
     // starting now 
     new Date(), 
     // 5 minutes 
     300000l 
     ); 
    } 
} 

也请注意,应用程序可能无法运行正是5分钟 - 看到文档的TimerTask。

0

你的解决方案是非常接近的工作,你只需要乘以计数器的延迟(你的情况,i):

public static void main(String[] args) 
{ 
    for (int i = 1; i <= 10; i++) // start i at 1 for initial delay 
    { 
     Timer timer = new Timer(); 
     timer.schedule(new TimerTask() { 
      public void run() 
      { 
       System.out.println("30 Seconds Later"); 
      } 
     }, 30000 * i); // 5 second intervals 
    } 
} 
2

Java已经在java.util.concurrent包中提供了一组丰富的API来实现这样的任务。其中一个API是ScheduledExecutorService。例如,考虑如下代码:此代码将执行每30秒后Runnabletask为高达5分钟:

import java.util.concurrent.*; 

class Scheduler 
{ 
    private final ScheduledExecutorService service; 
    private final long period = 30;//Repeat interval 
    public Scheduler() 
    { 
     service = Executors.newScheduledThreadPool(1); 
    } 
    public void startScheduler(Runnable runnable) 
    { 
     final ScheduledFuture<?> handler = service.scheduleAtFixedRate(runnable,0,period,TimeUnit.SECONDS);//Will cause the task to execute after every 30 seconds 
     Runnable cancel = new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       handler.cancel(true); 
       System.out.println("5 minutes over...Task is cancelled : "+handler.isCancelled()); 
      } 
     }; 
     service.schedule(cancel,5,TimeUnit.MINUTES);//Cancels the task after 5 minutes 
    } 
    public static void main(String st[]) 
    { 
     Runnable task = new Runnable()//The task that you want to run 
     { 
      @Override 
      public void run() 
      { 
       System.out.println("I am a task"); 
      } 
     }; 
     Scheduler sc = new Scheduler(); 
     sc.startScheduler(task); 
    } 
}  
0

我不知道,如果这个解决方案有问题与垃圾回收或没有,但我反正把它扔在这里。也许有人清楚,我也学到了一些东西。基本上,如果有剩余时间,定时器会设置一个新的定时器,并在5分钟后停止。

Main.java:

public class Main { 
    public static void main(String[] args) { 
     MyTimer myTimer = new MyTimer(300000,30000); 
     myTimer.startTimer(); 
    } 
} 

MyTimer.java:

import java.util.Timer; 
import java.util.TimerTask; 

public class MyTimer { 
    private int totalRunningTime; 
    private int currentTime = 0; 
    private int intervalTime; 

    private Timer timer = new Timer(); 

    public MyTimer(int totalRunningTime, int intervalTime) { 
     this.totalRunningTime = totalRunningTime; 
     this.intervalTime = intervalTime; 
    } 

    public void startTimer() { 
     startTimer(intervalTime); 
    } 

    private void startTimer(int time) { 
     timer.schedule(new TimerTask() { 
      public void run() { 

       if (currentTime <= totalRunningTime - intervalTime) { 
        printTimeSinceLast(intervalTime/1000); 
        currentTime += intervalTime; 
        startTimer(intervalTime); 
       } else if (currentTime < totalRunningTime) { 
        int newRestIntervalTime = totalRunningTime - currentTime; 
        printTimeSinceLast(newRestIntervalTime/1000); 
        currentTime += newRestIntervalTime; 
        startTimer(newRestIntervalTime); 
       } 
      } 
     }, time); 
    } 

    private void printTimeSinceLast(int timeSinceLast) { 
     System.out.println(timeSinceLast + " seconds later."); 
    } 
}