简体   繁体   中英

How do i put a limit on TimerTask rather than having it run forever?

I'm using the timer utility to repeatedly post output of a code. Right now I have it set to repeat nonstop on a 1 second interval. How could I change this to instead repeat until a time limit set by the user is reached?

//Create a new timer
Timer timer = new Timer();
static int interval = 1000; //Interval of timer in milliseconds
//Set the timer to start in 1 second and to go every certain amount of  milliseconds.
timer.scheduleAtFixedRate(TimerClass.timertask, 1000, interval);

As MadProgrammer has said; this can be achieved by using the TimerTask.cancel method from within your TimerTask.run method.

For example:

public class RunUntilInstantTimerTask extends TimerTask {
    private final Instant stopTime;

    public RunUntilInstantTimerTask(final Instant stopTime) {
        this.stopTime = Objects.requireNonNull(stopTime);
    }

    @Override
    public void run() {
        // Do scheduled stuff...

        if (Instant.now().isAfter(this.stopTime)) {
            this.cancel();
        }
    }
}

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