Android timer one thread only - java

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

Related

Java TimerTask in While Loop [duplicate]

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

Reuse a timer timertask Java

Soo created a timer using extending timertask.
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
timer.purge();
class MyTimeTask extends TimerTask
{
public void run(){
genReelNumbers();
laa++;
if(laa==50){
timer.cancel();
timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);}}}
timer.purge();
timer.schedule(new MyTimeTask(), 0, 50);}});
But im getting a error with the timer already canceled! As you can see i already tried to use the purge(), soo it cancels the "canceled" timers (dont know if that does make any sence). I want to use this timer each time that i press on the label! Any ideas?
First and foremost, this looks to be a Swing application, and if so, you shouldn't be using java.util.Timer and java.util.TimerTask since Swing is single-threaded, and the two classes above create a new thread or threads to achieve their actions, meaning that important code that should be called on the Swing event thread will not be called on this thread. This this risks causing pernicious intermittent and hard to debug threading exceptions to be thrown. Instead use a javax.swing.Timer. Then to stop this timer, simply call stop() on it, and to restart it, simply call start() on it. For more on this, please read: How To Use Swing Timers.
For example, I'm not 100% sure what you're code is supposed to be doing, but it could look something like:
// warning: code not compile- nor run-tested
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
// assuming a javax.swing.Timer field named timer
if (timer != null && timer.isRunning()) {
// if the timer is not null and it's running, stop it:
timer.stop();
}
// TIMER_DELAY is an int constant that specifies the delay between "ticks"
timer = new Timer(TIMER_DELAY, new ActionListener() {
#Override // this method will be called repeatedly, every TIMER_DELAY msecs
public void actionPerformed(ActionEvent e) {
genReelNumbers();
laa++;
if(laa==50){
timer.stop();
// timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);
}
}
});
timer.start();
}
});
after canceling the timer you have no other choice than creating a new object....
I followed the #Hovercraft advice and changed to javax.swing.Timer
It turned out like this:
//The variable "taxa" is the amount of times that i want it to do the task
javax.swing.Timer time1 = new javax.swing.Timer(taxa, new ActionListener() {
public void actionPerformed(ActionEvent e) {
genReelNumbers();
}
});
//starts the timer
time1.start();
//New timertask
TimerTask tt = new TimerTask() {
#Override
public void run() {
//stops the timer
time1.stop();
label_2.setVisible(false);
label_1.setVisible(true);
verificarodas();
}
};
Timer time = new Timer(true);
// the 2000 is how long i want to do the task's
//if i changed to 3000 it would take 3 seconds (remember it has to be a value on miliseconds) to do the 15 times, and soo on
time.schedule(tt, 2000);

How to change a java timer's interval

I'm working on an android Tetris game. And an IllegalStateException occurred when executing
timer.scheduleAtFixedRate (task, 0L, milliseconds);
in
public void setTimerInterval (int milliseconds) {
timer.cancel ();
timer = new Timer ();
timer.scheduleAtFixedRate (task, 0L, milliseconds);
}
Am I doing this wrongly or something?
I need to cancel the timer and create a new one because I cannot change the interval of the timer unless you schedule a new task for it, right?
I read a post here and here is a quote of one of the answers:
A timer can only be scheduled once. If IllegalStateException isn't happening when you call cancel(), but when you try to reschedule the timer, just reinstantiate the timer and then schedule it. Otherwise, I'm not sure.
I didn't use the accepted answer of the that question because it's about pausing and resuming the timer.
I reinstantiated the timer as shown above but there is still a IllegalStateException.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// do the task here
handler.postDelayed(this, milliseconds); // set time here to refresh textView
}
});
Make the milliseconds global and change that, maybe that would be a better solution.
How to change a java timer's interval
Java Timers don't have intervals. Timer tasks have intervals.
Solution: cancel and reschedule the TimerTask, not the Timer.

Make a Libgdx Timer run once

My Goal: Make one script wait .5 seconds, run, make another script wait .5 seconds, run.
The problem I am running into is that Timer.instance().clear(); makes the run() method only run once, on it's own it runs more than once. But, it also deletes Timer2 because it does not wait .5 seconds to run the code after the timer you scheduled (clear() removes all Timers/scheduled tasks). So, it ends up deleting the the Timer2 after .5 seconds.
Edit: Made a dumb error, I was not recognizing how the method was being called. I got it fixed :)
//Timer1
Timer.schedule(new Task(){
#Override
public void run() {
// \/ removes both Timer1 and Timer2
Timer.instance().clear();
}
}, .5f);
//Timer2
Timer.schedule(new Task(){
#Override
public void run() {
Timer.instance().clear();
}
}, 1f);
This works: "Make instance of timers: Timer timer1 = new Timer(); and Timer timer2 = new Timer(); then assign your schedules and code will run only once automatically. Like that: timer1.scheduleTask(....)" – aloupas

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