2017-07-24 69 views
-1

我正在尝试定期执行任务。例如:定时器无法执行任务

class MyTimerTask implements TimerTask 
{ 
    public void run() { 
    // Some actions to perform 
    } 
    Timer cleaner = new Timer(true); 
    cleaner.scheduleAtFixedRate(new MyTimerTask(), 0, PURGE_INTERVAL); 
} 

但是,run方法只执行一次。但是如果我第一次延迟10秒,那么run方法甚至不会执行一次。

例子:

cleaner.scheduleAtFixedRate(new MyTimerTask(), 10, PURGE_INTERVAL); 

回答

0

这听起来像是一个时间单位给我的问题。确保您正确转换为毫秒。

最简单的方法是使用Java的TimeUnit

Timer cleaner = new Timer(true); 
cleaner.scheduleAtFixedRate(new MyTimerTask(), 
    TimeUnit.SECONDS.toMillis(10), 
    TimeUnit.SECONDS.toMillis(30)); 

它也被Timer引起正在启动在守护进程模式。如果你所有的主要方法都设置了定时器,然后返回,定时器将永远不会执行,因为它是剩余的最后一个线程,因为它是一个守护进程线程,JVM将退出。

要解决这个问题,要么使计时器线程不是守护进程(即在构造函数中传递false),要么让主线程在退出之前等待用户输入。

下面是使用两种以上的例子:

public class TimerDemo extends TimerTask { 

    public void run() { 
     System.out.printf("Time is now %s%n", LocalTime.now()); 
    } 

    public static void main(String[] args) throws IOException { 
     Timer timer = new Timer(true); 
     timer.scheduleAtFixedRate(new TimerDemo(), 
       TimeUnit.SECONDS.toMillis(5), 
       TimeUnit.SECONDS.toMillis(10)); 
     System.out.printf("Program started at %s%n", LocalTime.now()); 
     System.out.println("Press enter to exit"); 
     try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { 
      // Wait for user to press enter 
      reader.readLine(); 
     } 
     System.out.println("Bye!"); 
    } 
} 

并运行它的输出:

Program started at 14:49:42.207 
Press enter to exit 
Time is now 14:49:46.800 
Time is now 14:49:56.799 
Time is now 14:50:06.799 
Time is now 14:50:16.799 
Time is now 14:50:26.799 
[I pressed 'enter'] 
Bye! 

Process finished with exit code 0 
+0

是的,你是对的Raniz。问题出在从main方法退出run方法不执行之后。所以,我必须把睡眠放在主线程中。 –

+0

如果它解决了您的问题,请随时接受我的答案。它通过在搜索结果中解决这个问题来帮助他人。 – Raniz

0

我有一个很难搞清楚究竟什么是你的问题,所以这可能不是你问什么了,但这种方法可能适合你:

public class MyTimerTask implements Runnable { 
    private static final TimeUnit timeUnit = TimeUnit.SECONDS; 
    private final ScheduledExecutorService scheduler; 
    private final int period = 10; 
    public static void main(String[] args) { 
     new MyTimerTask(); 
    } 
    public MyTimerTask() { 
     scheduler = Executors.newScheduledThreadPool(1); 
     scheduler.scheduleAtFixedRate(this, period, period, timeUnit); 
    } 
    @Override 
    public void run() { 
     // This will run every 10 seconds 
     System.out.println("Ran..."); 
    } 
} 
+0

所以是一个缺少@Override? – user7294900

+0

那么,你能举出一个“工作”的例子,因为你提供的代码不能运行,你在类声明等语句中。我不认为这就是为什么,因为它只是一个注释,让编译器给你更好的帮助。 – Lurr

相关问题