Sunny
Sunny

Reputation: 7604

Java Timer with timeout capability

I am implementing a timer:

timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //Do something;
                }
            },1000,1000);

But, I would like to have a timeout so that after lets say 100 tries/ 10 seconds, the timer stops automatically.

Thanks.

Upvotes: 1

Views: 16586

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try

    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        int n = 0;
        @Override
        public void run() {
            System.out.println(n);
            if (++n == 5) {
                timer.cancel();
            }
        }
    },1000,1000);

Upvotes: 4

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

I dont think we have java API for this in Timer class. You need to do it programmatically by implementing some custom logic based on your requirement.

Upvotes: 0

Ankit
Ankit

Reputation: 6622

start another timer, as soon as above timer starts, which cancels the above timer after 10sec. check to code below as a quick solution. but better you cancel the task() instead of timer.

timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    timer2.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        timer1.cancel();
                    }
            },0);
                    //Do something;
                }
            },1000,1000);

timer2 = new Timer();

Upvotes: 0

Rob
Rob

Reputation: 4947

You can simply have a variable outside the run method that keeps count of the iteration. Make an if statement inside the run() method that cancels the timer when it hits your desired amount. Increase the variable by one everytime the run() method executes.

Upvotes: 1

Related Questions