2

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
}
3
  • where dog677_Copy is defined? Commented Jul 22, 2015 at 14:48
  • Where is dog677_Copy , trm,tstnew defined? Commented Jul 22, 2015 at 14:49
  • @karthik these programs are defined in same location with complied state Commented Jul 22, 2015 at 15:01

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@MohitDarmwal I'm happy its helped and if it actually resolved your problem, please consider accepting it by clicking checkout mark next to votes. Of course it is optional

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.