Java Timer Stop the process at partuicular time - java

how to stop a timer in java at specific time?

Timer particularTimer = new Timer();
final Timer certainTimer = new Timer();//u can declare a final timer for certain process
particularTimer.schedule(new TimerTask() {
public void run(){
System.out.println("run particularTimer");
certainTimer.schedule(new TimerTask() {
public void run() {
System.out.println("run certainTimer");
}
}, 5000);// it's my start time in milliseconds
}
}, 5000);
//eg
Thread.sleep(6000);
particularTimer.cancel();//when u cancel the particularTimer,and u can cancel the certainTimer too.
certainTimer.cancel();

Related

Java - Recursively schedule a timer task

Is there a way to run a timer task only after the method completes. The method could take 10 seconds but the timer is set to run every 5 seconds. I want it to run again only after the 10 seconds are up.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
longRunningMethod();
timer.schedule(task, 0, 5000);
}
};
timer.schedule(task, 0, 10000);
You can use ScheduledExecutorService which has a scheduleWithFixedDelay() method which does exactly that.
"Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next."
So you could do
ExecutorService.newScheduledExecutor()
.submit(this::longRunningMethod, 0, 1000, ChronoUnit.MILLIS);
Removing the timer.schedule(task, 0, 5000); call will give you behavior you desire.
Your call of timer.schedule(task, 0, 10000); schedules repeating tasks every ten seconds.
You need to schedule one-shot timer tasks and create new TimerTask instance every time.
class MyTimerTask extends TimerTask {
private final Timer timer;
private final long nextScheduleDelay;
MyTimerTask(Timer timer, long nextScheduleDelay) {
this.timer = timer;
this.nextScheduleDelay = nextScheduleDelay;
}
#Override
public void run() {
longRunningMethod();
timer.schedule(new MyTimerTask(timer, nextScheduleDelay), nextScheduleDelay);
}
}
Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, 1000), 0);

Timer can not be repeated on android How to fix?

I want Timer execute repeat.
so I try this source
public static void init() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Looper.prepare();
recordWork();
Looper.loop();
}
};
Timer timer = new Timer();
timer.schedule(timerTask, 1000, 30000);
}
init() called when record button click.
why recordWork() only one execute?
this timer not execute repeat.
How to fix this problem?
thanks.
Use the function timer.scheduleAtFixedRate() to execute the timer every X seconds.
For example timer.scheduleAtFixedRate(timerTask, new Date(), 2000) to start the timer now and execute every 2 seconds.
Use it like below
public static void init() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Looper.prepare();
recordWork();
Looper.loop();
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 1000, 30000);
}
Use Timer as a global variable. and cancel it its need done.
if(timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
If you still can't fix your Timertask. Might as well give CountDownTimer a try
https://developer.android.com/reference/android/os/CountDownTimer.html
public void startCountDown() {
countDownTimer = new CountDownTimer(totalTimeinMillis,intervalBetweenCountdown) {
#Override
public void onTick(long millisUntilFinished) {
//execute repeating task here
}
#Override
public void onFinish() {
}
};
}
Use handler
Handler handler = new Handler();
int delay = 2000; //milliseconds
handler.postDelayed(new Runnable(){
public void run(){
recordWork();
handler.postDelayed(this, delay);
}
}, delay);

Can I run timer at different intervals of time?

Actually i wanted to ask can i give value from database to a timer delay?
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// whatever
}
}
});
}
};
timer.schedule(timerTask,2000,**myDelay**); //here at my delay
Here at myDelay, can i give different values through database? Or it must be fixed?
If you are to change the time all the time with different values, I suggest you use
schedule(TimerTask task, long time)
Everytime you have a new time from DB, just create a new Timer() like so
time = getNewTimeFromDB();
createNewTask(time);
....
private void createNewTask(long time) {
Timer timer=new Timer();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// whatever
}
});
}
};
timer.schedule(timerTask,time);
}
The good thing about this is you don't have to cancel the timer every single time because it is meant to run once.
May you should change your approach to the problem, create a function to return the time from the database FunctionToGetDelayFromDB();
Timer timer=new Timer();
long time = FunctionToGetTimeFromDB();
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// whatever
timer.schedule(timerTask, System.currentTimeMillis() + FunctionToGetDelayFromDB());
}
}
});
}
};
timer.schedule(timerTask, System.currentTimeMillis() + FunctionToGetDelayFromDB());
This should work for what you want to achieve...

Java timer.cancel() not stopping timer

I'm a novice at Java, and I've been trying to use java.util.timer to reset an existing timer after taking the right command input.
However, I've been unable to cancel the timertask properly, so the timer thread runs multiple instances of the timertask if the method is called multiple times. Any help would be appreciated.
Edit: I've changed the location of new Timer(), but it doesn't seem to have fixed it.
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
public static void main (String[] args) {
Timer timer = new Timer();
while (true) {
//BufferedReader to read input
//Something
if (input[0].equals("r")) {
time t = new time();
time.RestartTimer();
}
}
}
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
This is happening because you are creating a new instance of time class (time t = new time(); ) inside the while loop. Instead do this :
public static void main (String[] args) {
time t = new time(); // create an instance of time class
while (true) {
//Something
if (input[0].equals("r")) {
// call RestartTimer on the same in
t.RestartTimer();
}
}
}
Also inside RestartTimer() function you are creating new instance of Timer. Change it as follows :
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
time.RestartTimer(); statement won't be called until and unless either you change the modifier of method or call this method by using static object in main method. I think this is the only reason that your timer is not getting update.

How to stop the task scheduled in java.util.Timer class

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

Categories

Resources