I can run codes after every x seconds, but is there a way to only run a code once after x sec? Ex: I want to refresh a listview once after 1 second when a user click on a button?
Since the delayed operation is a UI Event, use a Handler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//my events
}
}, 2000); //time in millis
I usually recommend
Timer
class in time related stuffs. but in this case i wont recommend you to use Timer as you need to execute the operation only one.
Why not simply use a
Thread
and sleep it for 1000 millis. There you go. your 1 sec timer. :)
Related
I have two handlers running within an Android Service.
handler1 runs every 30 seconds
handler2 runs every 5 seconds
The problem is, handler2 can't run at the same time as handler1.
I mean, when handler2 reaches 30, 60, 90... secs it will run at the same time as handler1.
So, I need to find a way during those 30, 60 90 secs to run one handler after another.
I know a solution for this could be, but it's not elegant, neither accurate:
Run handler1 at second 0
Wait 7 seconds (or any other x # of secs no-multiple of 5)
Since handler2 runs more frequently than handler1 does, you can use counter in handler2 to track when to fire the events that you plan to trigger in handler1.
handler2.postDelayed(new Runnable() {
int count = 0;
#Override
public void run() {
if (count == 0) {
// fire handler1 events
}
count = (count+1) % 6;
}
}, 5);
How about using TimerTask and Timer to schedule repeated executions (every 5 seconds)? Depending on the interval, you run either the job currently done in handler1, or the one in handler2, or both. Perhaps you can break out these jobs into functions that are called from the TimerTask's run method. That would let the handler1 job run before the handler2 job, in a synchronized manner on the same thread.
Hey I am currently designing an app where some code gets executed every 200ms. The thread I use for this looks like this (simplified):
final Handler handler = new Handler();
Runnable runnable = new Runnable()
{ public void run()
{
handler.postDelayed(this, 200);
switch (status){
case 1: check(1);p2.setBackgroundColor(0x00000000); p1.setBackgroundColor(0xDDCC0000); status = 2; break;
case 2: check(2);p1.setBackgroundColor(0x00000000); p2.setBackgroundColor(0xAAAA0000); status = 1; break;
}
}
}; runnable.run();
check() contains some non-UI code lines.
The problem is, that the postDelayed-200-ms start, when the queue is fully executed and not at the beginning so all time that the system needs to execute the commands stacks and stacks all the time so these are actually ~210-230ms (depending on CPU load)
Then I tried to get the system date at the beginning of the thread and add 200ms to it but this results in some other, "heavier" errors.
I have no problem with more than 200ms delay, I just want to get it running stable.
I hope you understand my problem and can give some advice to me.
EDIT: I know got to know that the Handler runs acceptable (delay of 4ms on 200ms). The problem are the methods I am calling then. I will open a new question
If check() contains non-ui code lines then you should run those in a separate thread.
The bottom line is that the UI thread is *really busy, so, you can ask it to do something every 200ms but you aren't guaranteed any precision since the Device is doing its best to do all sorts of other things. When you say "heavier problems" what do you mean exactly?
I would try to start a Thread and just Log every 200ms to see if the device is willing to accurately do *anything at the rate you wish. If it does, then you can send messages to the UI thread to draw and if you find that its the drawing that is delayed, then perhaps you need to reduce your delay to give the UI thread time to finish drawing? (obviously this is also highly imprecise and will vary wildly from device to device).
Did you try doing it using Timers? A basic implementation would look like
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
}
}, 200, 200);
You can try using the alarm service as well. that should give you accurate (or at least consistent) results.
new Handler().postDelayed(new Runnable() {
public void run() {
//code
}
}, secondsDelayed * 1000);
here even if change value of 1000 to 100 or 10 thread runs for min 1sec.
This method postDelayed, has second parameter to let it know , in how much time it should start to run. not for how much time it should run, See Method info below
public final boolean postDelayed (Runnable r, long delayMillis)
Since: API Level 1
Causes the Runnable r to be added to the message queue, to be run after the
specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.
Parameters
r The Runnable that will be executed.
delayMillis The delay (in milliseconds) until the Runnable will be executed.
Returns
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped.
** Please also include "What you want to do" so one can also provide other possible solutions :)
I have a timer in my app which shut's down the app implemented with a handler to which I post a delayed runnable "quit". When user clicks the timer icon it should also show how much time is left. How could I get this data?
Should I implement an object which would count the seconds and use that data?
I prefer to use ScheduledExecutorService with ScheduledFuture, these API are more efficient and powerful than Handler and Timer IMO:
ScheduledExecutorService scheduledTaskExecutor = Executors.newScheduledThreadPool(1);
Runnable quitTask = new Runnable();
// schedule quit task in 2 minutes:
ScheduledFuture scheduleFuture = scheduledTaskExecutor.schedule(quitTask, 2, TimeUnit.MINUTES);
... ...
// At some point in the future, if you want to get how much time left:
long timeLeft = scheduleFuture.getDelay(TimeUnit.MINUTES);
... ...
Hope that helps.
Hello I have a ActionScript 3.0 project and I have a timer that is running on 1000 millisecond intervals. I would like to delay this timer for 1500 milliseconds perform an action and start the timer again after the delay. I thought I could do this easily, but I'm having trouble, would it be better to stop the timer and perform the action and then listen for the action to be completed to start the timer again?
If you have time, I would appreciate the help.
Thank you,
Scientific
Assuming I understood your question, why not something like this? (UNTESTED CODE)
yourTimer.addEventListener(TimerEvent.TIMER, itIsTime);
function itIsTime(evt:TimerEvent):void {
yourTimer.stop();
yourTimer.reset();
if(yourTimer.delay == 1500){
//Do your stuff
...
yourTimer.delay = 1000;
yourTimer.start();
} else {
//Do your stuff
...
yourTimer.delay = 1500;
yourTimer.start();
}
}
Alternatively you could use 2 timers, but the idea is the same, after 1000 do one thing, after 1500 do something different, controlling when each timer goes off with the other timer's listener function.