Stop Task after Timer is out - java

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.

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

Why for loop does not execute inside TmerTask

I want to repeat a for loop inside below code inside a service every some time ,but it print only one line and runs one time only
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 10000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
for (int i=0; i<10; i++){
Log.i("TAG", " inside method ");}
}
};
}
You are calling the following method.
public void schedule(TimerTask task, long delay)
So the task executes only once after delay.
If you want to execute it periodically you need to call the bellow method.(you may pass same value for delay and period)
public void schedule(TimerTask task, long delay, long period)
Your another query is it prints first line only. Most probably this is an issue with the Log. try System.out.print() instead of Log.i() to debug.
class MyTimerTask extends TimerTask {
private int counter = 1;
public void run() {
timerHandler.post(new Runnable() {
public void run() {
Toast.makeText(this, "" + counter, Toast.LENGTH_SHORT).show();
counter++;
}
});
if (counter == 10) {
myTimer.cancel();
myTimer.purge();
}
}
}
//Thats the usage like on ButtonClick
MyTimerTask myTimerTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTimerTask, 500, 1000);
Do you really need to run Loop ?

Java - stop Timer during user input (Countdown)

I have implemented a new class, and what I am trying to do is a countdown. This countdown should start before asking for user input. If it ends during the "waiting for user input", then the Timer should "return" a status or something similar to signal that the time is up. Therefore, I will not ask for the input again, but I skip a big part of my program.
Here is what I have:
public class Reminder
{
Timer timer;
public Reminder(int seconds)
{
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask
{
public void run()
{
System.out.println("Time's up!");
timer.cancel();
// here instead of System.exit(0), I should do something like "return status"
System.exit(0);
}
}
}
And where I call it:
Reminder rm = new Reminder(seconds);
do
{
x = Handler.getCoordinates(in, 'x');
y = Handler.getCoordinates(in, 'y');
// ... other stuff here
} while(!result);

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