简体   繁体   中英

java program is not getting called by timer itself

I have the below code here and I am trying to execute the whole program by itself on every second by using timer, but it is getting called only once. I called below program on first run by command prompt. Can you guys help me on this?

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
}

You should remove timer.cancel() from run() method. According to API documentation of cancel() method:

Note that calling this method from within the run method of a timer task that was invoked by this timer absolutely guarantees that the ongoing task execution is the last task execution that will ever be performed by this timer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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