Hello I am building an application that is going to execute a block of code at fixed periods of time (e.g. every 30 minutes). I would like that period to be strict,what I mean is that I would like to be guaranteed that the period will be 30 minutes and not 28 minutes or whenever the os whants to execute it.
I have a Timer object and use it as follows:
timer=new Timer();
timer.scheduleAtFixedRate(new GetLastLocation(), 0, this.getInterval());
where GetLastLocation is the handler class wich extends TimerTask.
This works fine,but I would like to be able to change the interval,what I am currently doing is using timer.scheduleAtFixedRate twice and changing the interval parameter to lets say a newInterval but I think that this is just having two timers execute every interval and new
Interval now, am I correct?
also I have tries cancelling the timer and then using the the method scheduleAtFixedRate() but this throws an exception as stated in the documentation.
what can I do to fix this?
regards maxsap
you can not schedule on a timer which was already cancelled or scheduled. You need to create a new timer for that.Timer timer;
synchronized void setupTimer(long duration){
if(timer != null) {
timer.cancel();
timer = null;
}
timer = new Timer();
timer.scheduleAtFixedRate(new GetLastLocation(), 0, duration);
}Now you can call setupTimer whenever you want to change the duration of the timer.PS: In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Define your task inside a TimerTask (as you did) and schedule the timer.
public final void checkFunction(){
t = new Timer();
tt = new TimerTask() {
#Override
public void run() {
//Execute code...
}
};
t.schedule(tt, 10*1000); /* Run tt (your defined TimerTask)
again after 10 seconds. Change to your requested time. */
}
Just execute the function wherever you want, for example in onCreate or in onResume/onStart.
You can also use handler instead of timertask.
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if(what.msg==1)
{
what.msg==2;
}
}
};
mHandler.sendEmptyMessageDelayed(1, 10* 1000);//10*1000 10 sec.specify your time
Related
I have a button on which I want to set the timer for 5 seconds for the first time and it should perform some task after completing 5 seconds. Also if user click button 2 times it should start timer for 10 seconds and after 10 seconds it should perform specific task. and if user click 3rd time it should stop all running timers. so I have do not know How to implement timer for one time
what I have search is this. But in this link it is continuously repeating after specific period of time, whereas I want to run once.
Now what I want
To start timer with first click (of 5 seconds)and if meanwhile user click 2nd time it should set timer with with new time period and if user click third time it cancels out all timers.
I do not want to use Thread timer using sleep method.
I want same behavior as there is in camera app in android 5.0 v.
So please tell me how to do this any code and source code would be appreciated.
In the link you provided you will find the answer if you try little harder.
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after);
So what you need to do is to maintain temporary variable to keep track of number of clicks and you can use second method like
For a repeating task:
new Timer().scheduleAtFixedRate(task, after, interval);
For a single run of a task:
new Timer().schedule(task, after * numberOfTimeBtnClked);
You have to pass the TimerTask method instead of task in that method.
**For updating your textview use below code and forget about whatever I have written above **
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//run in an interval of 1000ms
timer.schedule(timerTask, 0, 1000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
timerSince++; //global integer variable with default value 0
if(timerSince == 5 * numberOfBtnClick){
//call your method
timer.cancel;
timerSince = 0;
}else{
//textView.setText(((5 * numberOfBtnClick)-timerSince)+" second left");
}
});
}
};
}
}
On event start button click call:
startTimer();
I have a runnable class like this:
public class GetUpdatesThread implements Runnable{
#Override
public void run() {
//call a webservice and parse response
}
}
Which I want fire every 10 seconds for instance...
I would like to know how can I manage handlers or runnables or timers in my activity to acomplish this?
Thanks in advance!
You can use TimerTask and can implement like this.
int delay = 5000; // delay for 5 sec.
int period = 10000; // repeat every 10 secs.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("repeating");
}
}, delay, period);
You can use the timer method called scheduleAtFixedRate from this link. I am already using it inside my project and it works like charm. You just have to give a starting delay time and a period for it then it works.
You can use Handler and calling the sendEmptyMessageDelayed method. Here's a tutorial or two on using Handler. Also check out Updating the UI from a Timer from the official doc - it covers both approaches with TimerTask and Handler.
The best way to do this thing is to use AlarmManager class.
1) schedule a AlarmManager with serRepeat method. link for AlarmManager
2) set Broadcast receiver in Alarmmanager, it will call Receiver every particular time duration, now from Receiver you can start your thread .
if you use Timer task and other scheduler, Android will kill them after some time.
How can I reschedule a timer. I have tried to cancel the timer/timertask and and schedule it again using a method. But its showing an exception error:
Exception errorjava.lang.IllegalStateException: TimerTask is scheduled already
Code I have used it :
private Timer timer = new Timer("alertTimer",true);
public void reScheduleTimer(int duration) {
timer.cancel();
timer.schedule(timerTask, 1000L, duration * 1000L);
}
If you see the documentation on Timer.cancel() you'll see this:
"Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing."
You'll need to initialize a new Timer when you are rescheduling:
EDIT:
public void reScheduleTimer(int duration) {
timer = new Timer("alertTimer",true);
timerTask = new MyTimerTask();
timer.schedule(timerTask, 1000L, duration * 1000L);
}
private class MyTimerTask extends TimerTask {
#Override
public void run() {
// Do stuff
}
}
In fact, if you look in the cancel method javadoc, you can see the following thing :
Does not interfere with a currently executing task (if it exists).
That tells the timer "ok, no more tasks now, but you can finish the one you're doing". I think you'll also need to cancel the TimerTask.
#Eric Nordvik answer is running fine.
One thing we can do is to cancel previous timer events execution
public void reScheduleTimer(int duration) {
// Cancel previous timer first
timer.cancel();
timer = new Timer("alertTimer",true);
timerTask = new MyTimerTask();
timer.schedule(timerTask, 1000L, duration * 1000L);
}
Actually you can use purge() so you don't have to initialize a new Timer.
public int purge ()
Added in API level 1
Removes all canceled tasks from the task queue. If there are no other references on the tasks, then after this call they are free to be garbage collected.
Returns the number of canceled tasks that were removed from the task queue.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm developing an application which sends a message to a specific number in a specific period of time. The problem is that it continues sending that message after that period of time. How would I stop the timer after that specific time in order to stop sending that message?
CountDownTimer waitTimer;
waitTimer = new CountDownTimer(60000, 300) {
public void onTick(long millisUntilFinished) {
//called every 300 milliseconds, which could be used to
//send messages or some other action
}
public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();
to stop the timer early:
if(waitTimer != null) {
waitTimer.cancel();
waitTimer = null;
}
and.. we must call "waitTimer.purge()" for the GC. If you don't use Timer anymore, "purge()" !! "purge()" removes all canceled tasks from the task queue.
if(waitTimer != null) {
waitTimer.cancel();
waitTimer.purge();
waitTimer = null;
}
In java.util.timer one can use .cancel() to stop the timer and clear all pending tasks.
We can schedule the timer to do the work.After the end of the time we set the message won't send.
This is the code.
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//here you can write the code for send the message
}
}, 10, 60000);
In here the method we are calling is,
public void scheduleAtFixedRate (TimerTask task, long delay, long period)
In here,
task : the task to schedule
delay: amount of time in milliseconds before first execution.
period: amount of time in milliseconds between subsequent executions.
For more information you can refer:
Android Developer
You can stop the timer by calling,
timer.cancel();
I had a similar problem: every time I push a particular button, I create a new Timer.
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
Exiting from that activity I deleted the timer:
if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}
But it was not enough because the cancel() method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge() method was not useful for me.
I solved the problem just checking the Timer instantiation:
if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}
It says timer() is not available on android? You might find this article useful.
http://developer.android.com/resources/articles/timed-ui-updates.html
I was wrong. Timer() is available. It seems you either implement it the way it is one shot operation:
schedule(TimerTask task, Date when) // Schedule a task for single execution.
Or you cancel it after the first execution:
cancel() // Cancels the Timer and all scheduled tasks.
http://developer.android.com/reference/java/util/Timer.html
I had a similar problem and it was caused by the placement of the Timer initialisation.
It was placed in a method that was invoked oftener.
Try this:
Timer waitTimer;
void exampleMethod() {
if (waitTimer == null ) {
//initialize your Timer here
...
}
The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.
I am currently trying to set up a WiFi Scan in my Android application that scans for WiFi access points every 30 seconds.
I have used Timer and TimerTask to get the scan running correctly at the intervals which I require.
However I want to be able to stop and start the scanning when the user presses a button and I am currently having trouble stopping and then restarting the Timer and TimerTask.
Here is my code
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.scan(context);
Log.d("TIMER", "Timer set off");
}
});
}};
t.schedule(scanTask, 300, 30000);
}
public void stopScan(){
if(scanTask!=null){
Log.d("TIMER", "timer canceled");
scanTask.cancel();
}
}
So the Timer and Task start fine and the scan happens every 30 seconds however I cant get it to stop, I can stop the Timer but the task still occurs and scanTask.cancel() doesn't seem to work either.
Is there a better way to do this? Or am I missing something in the Timer/TimerTask classes?
You might consider:
Examining the boolean result from calling cancel() on your task, as it should indicate if your request succeeds or fails
Try purge() or cancel() on the Timer instead of the TimerTask
If you do not necessarily need Timer and TimerTask, you can always use postDelayed() (available on Handler and on any View). This will schedule a Runnable to be executed on the UI thread after a delay. To have it recur, simply have it schedule itself again after doing your periodic bit of work. You can then monitor a boolean flag to indicate when this process should end. For example:
private Runnable onEverySecond=new Runnable() {
public void run() {
// do real work here
if (!isPaused) {
someLikelyWidget.postDelayed(onEverySecond, 1000);
}
}
};
using your code, instead of
scanTask.cancel();
the correct way is to cancel your timer (not timerTask):
t.cancel();
The Android documentation says that cancel() Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing. Which explains the issue.