Description: I am trying to stop the timer from running once i=10 with a while loop. This is only a test. In my project, I am actually going to use the timer to check a boolean value from an online database and stop the timer once "true" is returned.
Code:
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
int i = 0;
@Override
public void run() {
System.out.println("Timer ran for:" + ++i);
}
};
while (i < 10) {
timer.schedule(task, 0, 1000);
}
}
Output:
Timer ran for:1
Exception in thread "main" java.lang.IllegalStateException: Task already scheduled or cancelled
at java.base/java.util.Timer.sched(Timer.java:402)
at java.base/java.util.Timer.schedule(Timer.java:249)
at Code.testUtilTimer.main(testUtilTimer.java:31)
Timer ran for:2
Timer ran for:3
Timer ran for:4
Timer ran for:5
Timer ran for:6
Timer ran for:7
Timer ran for:8
Timer ran for:9
Timer ran for:10
Timer ran for:11
In my opinion you don't need to use while loop. Already schedule will work at certain time intervals. If you do as in my example, you will solve your problem.
TimerTask task = new TimerTask() {
public void run() {
boolean dbValue = //Database operations
if(dbValue) {
cancel();
}
}
};
Timer timer = new Timer("Timer");
timer.scheduleAtFixedRate(task, 1000L, 1000L);