Postponing timer schedule java - java

At TIME = 0, a user calls a method that sets a flag after 10 seconds. (at TIME = 10)
If the user calls the method again at TIME = 2 the flag should NOT be set at TIME = 10, but instead at TIME = 12:
boolean myFlag; // initializes to false
private Timer timer;
public void setFlag() {
// remove old timer if there was one
if (timer != null) { timer.cancel(); timer = null; }
// set the new timer
timer = new Timer();
TimerTask tt = new TimerTask() {
#Override
public void run() { myFlag = true; }
};
timer.schedule(tt, 10000);
}
Are there any cleaner ways to implement this "updated-schedule-time" model? Examples are appreciated.

I would have simply kept it the same but made little changes.
Declare the variables always as variables should be declared and initialized near they are first used.
public void setFlag() {
Timer timer;
timer = new Timer();
// remove old timer if there was one
if (timer != null) { timer.cancel(); }
// set the new timer
TimerTask tt = new TimerTask() {
#Override
public void run() { setFlag(); }
};
timer.schedule(tt, 10000);
}

Related

Change length of Countdowntimer

I want to change the length of my Countdowntimer when it finishs. So I got a Random Number which changes everytime.
standby_time = 15000
standby_counter = new CountDownTimer(standby_time,1000) {
#Override
public void onTick(long millisUntilFinished) {
++standby_zaehler;
}
#Override
public void onFinish() {
...
standby_zaehler = 0;
rndm_groesse = 60000;
random_zahl = r.nextInt(rndm_groesse);
standby_time = random_zahl;
standby_counter.start();
}
};
Where is my fault ? The time is not changing and takes the first value (15sec)
The countdown timers time isnt ment to be changed. You can recreate the timer to alter the time but because you are looking to start it again inside the onFinish() method it would be wise to use a different implementation better suited for this task. The java.util.Timer class does this well.
private Timer timer = new Timer();
private int standby_zaehler = 0;
private Random r = new Random();
public void scheduleNextTimer() {
// reset our countdown
standby_zaehler = 0;
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// 1 second passed, remove it to the countdown
--standby_zaehler;
// we are finished counting down. get a new max seconds
if(standby_zaehler < 0) {
standby_zaehler = r.nextInt(60);
}
}
}, 1000, 1000);
}
As you can see we dont even need to create a new timer, just reset the number and begin again.

How to change android timer period?

I am writing simple game, where some action must accelerating during the process. The question is how to change timer's period?
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//
// I need to change timer's period here
//
}
});
}
};
timer.schedule(timerTask, 0, period);
Will be glad to hear any advices.
I assume that you are performing some logic within the run() method of the TimerTask.
I think a simpler way to go about this would be to use a Handler. This is possibly more idiomatic for Android:
private final Handler mHandler = new Handler();
private final Runnable mTask = new Runnable() {
#Override
public void run() {
// Do your logic.
// Now post again.
mHandler.postDelayed(mTask, /* choose a new delay period */);
}
};
public void init() {
delay = 1000L; // 1 second.
mHandler.postDelayed(mTask, delay);
}

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.

Associating timer with tables

I am new to timer's and don't know much about them .My problem is i am creating 2 tables dynamically, and when ever a table is create a timer for 10 mins is assigned to it. I.e. the user has to fill that table in 10 mins else the table will be destroyed. I tried a making a small demo in which i print stuff
The code is :
final Timer mytimers = new Timer();
Timer mytimers1 = new Timer();
mytimers1 = new Timer();
final long delay1 = 5*1000;
// mytimers = new Timer();
mytimers.schedule(new TimerTask() {
Long current1 = System.currentTimeMillis();
long check = current1;
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println(current);
System.out.println("\n");
if((current1 + delay1)<current)
{
System.out.println("mytimmer is about to stop");
mytimers.cancel();
}
}
}, 100, 1000);
mytimers1.schedule(new TimerTask() {
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println("in" + current);
}
}, delay1, 1000);
}
but when i tried implementing this int he final project it does not work as i have to make any variable inside the run a final , thus its value can not to be changed !!!
Please let what should i do !!Thank you
i have to make any variable inside the run a final , thus its value can not to be changed!
Either turn these variables into member variables or encapsulate these values in a proper class, instantiate the class and give a reference to that object to the timer task.
Even though the reference is final, the timer task will still be able to do things such as myTableController.destroyTable().
do it like this :
class YourClass{
Timer mytimers = new Timer();
Timer mytimers1 = new Timer();
long delay1 = 5*1000;
mytimers.schedule(new TimerTask() {
Long current1 = System.currentTimeMillis();
long check = current1;
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println(current);
System.out.println("\n");
if((current1 + delay1)<current) {
System.out.println("mytimmer is about to stop");
mytimers.cancel();
}
}
}, 100, 1000);
mytimers1.schedule(new TimerTask() {
#Override
public void run() {
Long current = System.currentTimeMillis();
System.out.println("in" + current);
}
}, delay1, 1000);
}
in your case you have created anonymous 'concrete' class ie TimerTask, and you are trying to access variables which are not in its scope.
So, if the variables you are trying to access are local(method) variables then they should be declared final or the other way around is to declare those variables as instant(member) variables that what i have done above.

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