Java TimerTask in While Loop [duplicate] - java

I am using java.util.Timer class and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.
How should I do that?

Keep a reference to the timer somewhere, and use:
timer.cancel();
timer.purge();
to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.
private static int count = 0;
public static void run() {
count++;
if (count >= 6) {
timer.cancel();
timer.purge();
return;
}
... perform task here ....
}

Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.

You should stop the task that you have scheduled on the timer:
Your timer:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
#Override
public void run() {
//do something
};
};
t.schedule(tt,1000,1000);
In order to stop:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Notice that just cancelling the timer will not terminate ongoing timertasks.

Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);

Related

Stop Task after Timer is out

How can I stop my Task when the Timer is out or if the algorithm is finished? The Object (Student) has a long variable "dyingTime". After Time is over it should print it out. Or if the algorithm is over it should print out something else.
Here is my code:
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
if (run) {
doAlgorithm();
sysout(" Beendet ", timeStart);
} else {
timer.cancel();
timer.purge();
sysout(" Tot ", timeStart);
}
}
}; timer.schedule(timerTask, 0, dyingTime);
Where do i put run = false?
Right now the algorithm goes only 5 millisecs, although the dyingTime is set to 1000.

Android timer one thread only

I'm having problem with Android timer's scheduleAtFixedRate option.
Timer timer = new Timer();
TimerTask myTimerTask = new TimerTask() {
public void run() {
...
}
};
timer.scheduleAtFixedRate(myTimerTask, 0, 5000);
This snippet is doing bad things for me. It's executed in the service so every time method is called timer creates a new thread and executes the same code while the old thread is still running; that creates performance problems. I need to run the code in the run() method every 5 seconds but I want the old task to be canceled. Is there any way to handle this problem ?
You can use the timer.cancel() to stop the timer.
For example, I had an end button to finish the timer early:
finishEarlyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
timer.cancel();
}
});

Java Timer Usage

Hi I am using a timer for 2 tasks, which will monitor a set of IP address
public input ()
{
timer.schedule(task, 0, 8);
timer_second.schedule(task_monitor, 0, 5);
}
and I have 2 Timer Task
private final TimerTask task = new TimerTask() {
#Override
public void run() {
}
}
private final TimerTask task2 = new TimerTask() {
#Override
public void run() {
}
}
But as per my code logic, input () can be called more than one time , and if i call second time i get IllegalStateException: Task already scheduled or cancelled
Which seems to be obvious, but my logic is input can be called by different IP's and i have to monitor all such IP's using the 2 Timer Task
How should I avoid This ??
Please Help !!!!!
Thanks in advance

Creating a timer and cannot restart it

I've created GUI timer, it runs exactly how I wanted it to. I have a stop and pause button, when I stop or pause the timer and restart a new one I get Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Task already scheduled or cancelled
I'm unsure what I'm suppose to do I've read you cant reuse tasks, but I have no clue to solve this. Can someone PLEASE help me out I'm going crazy over this, I always seem to fix one problem but another one pops up.
Heres part of my code which does the countdown
private TimerTask task = new TimerTask(){
#Override
public void run(){
if (countdown()) {
if(minutes < 9 && seconds < 9)
timerOutput.setText("0"+minutes + ": 0" + seconds);
else if(minutes < 9)
timerOutput.setText("0"+minutes + ":" + seconds);
else if(seconds < 9)
timerOutput.setText(minutes + ": 0" + seconds);
}
else
{
System.out.println("Finish!");
timerOutput.setText("Time is up!");
timer.cancel();
startBut.setEnabled(true);
}
}
};
private boolean countdown(){
seconds --;
if (seconds < 0){
minutes--;
seconds = 59;
if (minutes == -1){
return false;
}
}
return true;
}
Well TimerTasks aren't designed to be reused. The best you can do is create a new TimerTask every time you're going to reschedule it.
Although you can't simply restart a Timer, you could create a Timer wrapper class which would act exactly like a Timer but allow a simple restart method that would instantiate a new Timer in the background. For example;
public class RestartableTimer{
private Timer timer;
private long delay, period;
public RestartableTimer(){
timer = new Timer();
}
public void scheduleAtFixedRate(TimerTask task, long delay, long period){
this.delay = delay;
this.period = period;
timer.scheduleAtFixedRate(task, delay, period);
}
public void restart(TimerTask task){
timer.cancel();
timer = new Timer();
timer.scheduleAtFixedRate(task, delay, period);
}
}
A fair warning, this would not allow for polymorphism. You couldn't for example store a RestartableTimer in a Timer reference. You will also still need to instantiate a new TimerTask when you restart. If you wanted (and you knew you would only be reusing the same TimerTask), you could declare a custom and private embedded class in the above and let the wrapper class handle the creation of the new TimerTask. Alternatively you could have the class methods take a TimerTaskFactory which would implement an Interface which required a method that returned a TimerTask.
Below, an example of using the above class;
public static void main(String[] args) throws InterruptedException{
TimerTask task = new TimerTask(){
#Override
public void run() {
System.out.println("Running");
}};
RestartableTimer rt = new RestartableTimer();
System.out.println("Timer starting with one task");
rt.scheduleAtFixedRate(task, 1000, 1000);
Thread.sleep(5000);
System.out.println("Timer restarting with another task");
rt.restart(new TimerTask(){
int count = 0;
#Override
public void run() {
if(count>4) {
System.out.println("Done");
this.cancel();
} else {
System.out.println("Running 2");
count++;
}
}});
}

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.
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);
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.
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();
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.

Categories