TimerTask start stop only executing once - java

Problem, I can only execute my timer once. I know its because I called the function timer2.cancel(); and timer1.cancel(); :: Cancel being "Never run this ever again". I need a replacement function, one that actually stops a timer, but can be started back up again when I reschedule it. How do I go about doing that?
public void actionPerformed (ActionEvent e){
if (e.getSource()==jbtStart)
{
System.out.println("Start is pressed");
timer2.cancel();
timer1.schedule(new Task(), 0, delay);
}
else if (e.getSource()==jbtStop)
{
System.out.println("Stop is pressed");
timer1.cancel();
timer2.schedule(new Task2(), 0, delay);
}

Why not just create a new Timer at that point? Either that, or keep hold of the TimerTask as well as the timer, and cancel that instead of the timer itself.
As a third possible alternative, have a single timer task and a single timer, but make the timer task aware of what it's meant to do at any point - it looks like you're effectively toggling what you want to do each time the timer ticks. You could always keep two separate classes to separate the logical functionality, and then have a "wrapper" task which allows you to replace what behaviour is executed on each run.

I would cancel the TimerTasks instead of the Timers (and I would use only one Timer).
UPDATE:
private Task task1;
private Task2 task2;
public void actionPerformed (ActionEvent e){
if (e.getSource()==jbtStart)
{
System.out.println("Start is pressed");
if (task2 != null) {
task2.cancel();
}
task1 = new Task();
timer.schedule(task1, 0, delay);
}
else if (e.getSource()==jbtStop)
{
System.out.println("Stop is pressed");
if (task1 != null) {
task1.cancel();
}
task2 = new Task2();
timer.schedule(task2, 0, delay);
}

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

Cancel anonymous TimerTask

boolean timing = true; /* this is a global attribute and its only here for context */
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Platform.runLater(() -> {
new Thread(() -> {
if (!timing) {
try {
tt.cancel(); /* I want to cancel this if timming is false*/
} catch (Exception e) {
e.printStackTrace();
}
} else {
update();
}
}).run();
});
}
}, 10, 10);
I want to know if is possible to cancel that particular TimerTask inside of itself, please note that "tt" is only an example, I didn't know what else to call it. thanks.
Timers have their own background threads. Unless your tasks take a very long time to run, you do not need to create a new thread within the #run() method of the task (and you should not).
You can cancel subsequent executions of the timer by making the instance final:
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
// Do work.
if (!timing) {
t.cancel();
}
}
});
(Exception handling omitted for brevity.)
If you only want to cancel the task itself (allowing other tasks scheduled by the timer to continue running), it's a trivial call to the #cancel() method of the task instance:
if (!timing) {
this.cancel();
}
You should also ensure that your timing variable is declared volatile. If you don't, the value could be cached in each thread, and you won't be able to observe changes.
How about you make a new method to cancel the Timer?
private void cancelTimer(Timer t)
{
t.cancel();
}
You also need to make the Timer final.

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

Pausing/stopping and starting/resuming Java TimerTask continuously?

I have one simple question regarding Java TimerTask. How do I pause/resume two TimerTask tasks based on a certain condition? For example I have two timers that run between each other. When a certain condition has been met inside the task of first timer, the first timer stops and starts the second timer, and the same thing happens when a certain condition has been met inside the task of second timer. The class below shows exactly what I mean:
public class TimerTest {
Timer timer1;
Timer timer2;
volatile boolean a = false;
public TimerTest() {
timer1 = new Timer();
timer2 = new Timer();
}
public void runStart() {
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
}
class Task1 extends TimerTask {
public void run() {
System.out.println("Checking a");
a = SomeClass.getSomeStaticValue();
if (a) {
// Pause/stop timer1, start/resume timer2 for 5 seconds
timer2.schedule(new Task2(), 5000);
}
}
}
class Task2 extends TimerTask{
public void run() {
System.out.println("Checking a");
a = SomeClass.getSomeStaticValue();
if (!a) {
// Pause/stop timer2, back to timer1
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
}
// Do something...
}
}
public static void main(String args[]) {
TimerTest tt = new TimerTest();
tt.runStart();
}
}
So my question is, how do I pause timer1 while running timer2 and vice versa while timer2 is running? Performance and timing is my main concern as this needs to be implemented inside another running thread. By the way I am trying to implement these concurrent timers on Android.
Thanks for your help!
From TimerTask.cancel():
Note that calling this method from
within the run method of a repeating
timer task absolutely guarantees that
the timer task will not run again.
So once cancelled, it won't ever run again. You'd be better off instead using the more modern ScheduledExecutorService (from Java 5+).
Edit: The basic construct is:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(runnable, 0, 1000, TimeUnit.MILLISECONDS);
but looking into it there's no way of cancelling that task once its started without shutting down the service, which is a bit odd.
TimerTask might be easier in this case but you'll need to create a new instance when you start one up. It can't be reused.
Alternatively you could encapsulate each task as a separate transient service:
final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
Runnable task1 = new Runnable() {
public void run() {
a++;
if (a == 3) {
exec.shutdown();
exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(task2, 0, 1000, TimeUnit.MILLISECONDS)
}
}
};
exec.scheduleAtFixedRate(task1, 0, 1000, TimeUnit.MILLISECONDS);
easiest solution i found: just add a boolean in the run code in the timer task, like so:
timer.schedule( new TimerTask() {
public void run() {
if(!paused){
//do your thing
}
}
}, 0, 1000 );
If you have already canceled one timer, you can't re-start it, you'll have to create a new one.
See this answer, it contains a video and the source code how I did something similar.
Basically there are two method: pause and resume
In pause:
public void pause() {
this.timer.cancel();
}
In resume:
public void resume() {
this.timer = new Timer();
this.timer.schedule( aTask, 0, 1000 );
}
That makes the perception of pause/resume.
If your timers perform different actions based on the state of the application you may consider use the StatePattern
Fist define a abstract state:
abstract class TaskState {
public void run();
public TaskState next();
}
And provide as many states as you like. The key is that one state leads you to another.
class InitialState extends TaskState {
public void run() {
System.out.println( "starting...");
}
public TaskState next() {
return new FinalState();
}
}
class FinalState extends TaskState {
public void run() {
System.out.println("Finishing...");
}
public TaskState next(){
return new InitialState();
}
}
And then you change the state in your timer.
Timer timer = new Timer();
TaskState state = new InitialState();
timer.schedule( new TimerTask() {
public void run() {
this.state.run();
if( shouldChangeState() ) {
this.state = this.state.next();
}
}
}, 0, 1000 );
Finally, if what you need is to perform the same thing, but at different rates, you may consider using the TimingFramework. It is a bit more complex but let's you do cool animations, by allowing the painting of certain component take place at different rates ( instead of being linear )
In my opinion, this is somewhat misguided. If your code needs time guarantees, you can't use Timer anyway, nor would you want to. "This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method."
The answer, IMHO, is that you don't want to pause and restart your timers. You just want to suppress their run methods from doing their business. And that's easy: you just wrap them in an if statement. The switch is on, they run, the switch is off, they miss that cycle.
Edit: The question has shifted substantially from what it was originally, but I'll leave this answer in case it helps anyone. My point is: if you don't care when your event fires in the N millisecond span (just that it doesn't EXCEED once every N milliseconds), you can just use conditionals on the run methods. This is, in fact, a very common case, especially when N is less than 1 second.
Reviewing your source code, here are the changes ( which pretty much validate my previous answer )
In task1:
// Stop timer1 and start timer2
timer1.cancel();
timer2 = new Timer(); // <-- just insert this line
timer2.scheduleAtFixedRate(new Task2(), 0, 1000);
and in task2:
// Stop timer2 and start timer1
timer2.cancel();
timer1 = new Timer(); // <-- just insert this other
timer1.scheduleAtFixedRate(new Task1(), 0, 1000);
It runs on my machine:
Android won't reuse a TimerTask that has already been scheduled once. So it's necessary to reinstantiate both the Timer and TimerTask, for example like this in a Fragment:
private Timer timer;
private TimerTask timerTask;
public void onResume ()
{
super.onResume();
timer = new Timer();
timerTask = new MyTimerTask();
timer.schedule(timerTask, 0, 1000);
}
public void onPause ()
{
super.onPause();
timer.cancel(); // Renders Timer unusable for further schedule() calls.
}
I am able to stop a timer and a task using following code:
if(null != timer)
{
timer.cancel();
Log.i(LOG_TAG,"Number of cancelled tasks purged: " + timer.purge());
timer = null;
}
if(task != null)
{
Log.i(LOG_TAG,"Tracking cancellation status: " + task.cancel());
task = null;
}
Timer timer1;
private boolean videoCompleteCDR=false;
private boolean isVideoPlaying=false;
int videoTime=0;
private int DEFAULT_VIDEO_PLAY_TIME = 30;
#Override
public View onCreate(){
isVideoPlaying = true; //when server response is successfully
}
#Override
public void onPause() {
super.onPause();
if(isVideoPlaying ) {
if(this.timer1 !=null) {
this.timer1.cancel();
}
}
}
#Override
public void onResume() {
super.onResume();
if(isVideoPlaying && !videoCompleteCDR) {
callTimerTask();
}
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
printLog( "GameFragment visible ");
if(isVideoPlaying && !videoCompleteCDR) {
callTimerTask();
}
} else {
printLog("GameFragment in visible ");
if(isVideoPlaying) {
if(this.timer1 !=null) {
this.timer1.cancel();
}
}
}
}
private void callTimerTask() {
// TODO Timer for auto sliding
printLog( "callTimerTask Start" );
timer1 = new Timer();
timer1.schedule(new TimerTask() {
#Override
public void run() {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (getActivity() == null) {
return;
}
videoTime++;
if(DEFAULT_VIDEO_PLAY_TIME ==videoTime){
videoCompleteCDR=true;
Log.e("KeshavTimer", "callTimerTask videoCompleteCDR called.... " +videoTime);
destroyTimer();
}
Log.e("KeshavTimer", "callTimerTask videoTime " +videoTime);
}
});
} else {
printLog("callTimerTask getActivity is null ");
}
}
}, 1000, 1000);
// TODO 300, 2000;
}
private void destroyTimer(){
this.timer1.cancel();
}

Categories