程序本身不会调用java程序

时间:2015-07-22 14:22:50

标签: java timer timertask

我在这里有下面的代码,我试图通过使用计时器每秒执行整个程序,但它只被调用一次。我首先通过命令提示符调用下面的程序。你能帮帮我吗?

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

public class Task3 {
    public static void main(String[] args)  {
        final  Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // task to run goes here
                System.out.println("Hello !!!");
                try {
                    dog677_Copy.main(new String[0]);
                    try {
                        Thread.sleep(1000);                 //1 min .
                    }
                    catch(InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                    trm.main(new String[0]);
                    tstnew.main(new String[0]);

                    timer.cancel();
                    timer.purge();

                } catch (Exception ex) {
                    // handle the exception,
                    // in this case by throwing a RuntimeException with ex as cause
                    throw new IllegalStateException("I didn't expect a exception.", ex);
                }
            }
        };

        long delay = 0;
        long intevalPeriod = 1 * 240000;

        // schedules the task to be run in an interval 
        // timer.scheduleAtFixedRate(task, delay,intevalPeriod);
        timer.schedule(task, 0, 1000);

        System.out.println("Hello !!!");
    } // end of main
}

1 个答案:

答案 0 :(得分:3)

您应该从timer.cancel()方法移除run()。根据{{​​1}}方法的API documentation

  

请注意,在计时器的run方法中调用此方法   这个计时器调用的任务绝对保证了   正在进行的任务执行是最后一次执行任务   由此计时器执行。