I'am strugeling with making delays in GWT (client-side).
What I want is to have a break of a few seconds between the iterations of a for-loop.
The first iteration should start instantly, but there has to be a pause between the following ones.
Anyone an idea?
You can delay by using Timer.
Try something like this:
Timer timer = new Timer() {
public void run {
// Whatever code you want to repeat
}
};
for(int i=0; i<10; i++) {
timer.schedule(100) //100 millisecond delay
}
Threading concept could be used for your question
you could try having a counter of loop and check for condition inside loop that if counter is >1 the use thread sleep for some seconds...
Related
I want to have a thread that loops at a constant amount of times per second for example a render loop that aims for a constant framerate. The loop would obviously slow if the time it takes exceeds the time allowed.
Thanks.
How about
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(0, delay, TimeUnit.MILLI_SECONDS, new Runnable() {
public void run() {
// do something
}
});
or
long delay = ....
long next = System.currentTimeMillis();
while(running) {
// do something
next += delay;
long sleep = next - System.currentTimeMillis();
if (sleep > 0)
Thread.sleep(sleep);
}
There are two basic techniques you need two consider:
seperate updateing your model or state of the world from rendering it.
If you have done that, you can sleep/wait the appropriate amount of time before rendering stuff or skip the rendering for some frames if you fall behind your planed schedule.
I can recommend two good tututorials on how to implement something like a game loop in java/android.
First one about the basics is http://obviam.net/index.php/a-very-basic-the-game-loop-for-android/
and the second one has a focus on constant Frames per Second: http://obviam.net/index.php/the-android-game-loop/. I think the lessons apply to regualar java as well.
I set up a timer to perform a task every 10 seconds within a loop. Also, this is inside a broadcastReceiver, not the MainActivity.
doSomething() {
public void onSuccess(int[] arr) {
for (int i = 0; i<arr.length(); i++) {
<wait 10 seconds>
<show some message>
} // if i == 3, the loop should take 30 seconds to perform
}
}
I tried creating a new thread AND making a timer, but neither solution waits ten seconds for a task inside a loop. I have also tried doing Thread.sleep(10000) without creating a new thread, but this makes the main UI freeze for ten seconds before each task is performed. Could anyone lead me to the right direction?
Edit: this is a possible duplicate of this. My question, in other words, is that is it not possible to do a delayed task inside a loop? If so, why?
try this one count down timer http://developer.android.com/reference/android/os/CountDownTimer.html
Im trying to get a timer to work in my current java project that adds 1 to an integer variable every n microseconds (e.g. 500 for 1/2 a second), within an infinite loop, so that it is always running while the program runs.
Heres the code i have currently:
public class Ticker
{
public int time = 0;
long t0, t1;
public void tick(int[] args)
{
for (int i = 2; i < 1; i++)
{
t0 = System.currentTimeMillis();
do
{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < 500);
time = time + 1;
}
}
}
Everyone was so helpful with my last question, hopefully this one is just as easy
Here is an comparable ScheduledExecutorService example which will update the time variable with a 500 millisecond interval:
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(new Runnable(){
private int time = 0;
#Override
public void run(){
time++;
System.out.println("Time: " + time);
}
}, 0, 500, TimeUnit.MILLISECONDS);
This approach is preferred over using Timer.
I think you want
Thread.sleep(500);
At the moment you're consuming CPU cycles waiting for 500ms (you mention microseconds but I believe you want milliseconds). The above puts your current thread to sleep for 500ms and your process won't consume any CPU (or minimal at least - garbage collection will still be running). If you watch the CPU when you run your version you should see the difference.
See here for more info.
If you need to do it in a different thread, take a look on Timer:
int delay = 500; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
time++
}
};
new Timer(delay, taskPerformer).start();
Note that the code above cannot utilize a local variable (they must be declared as final to access them in an anonymous class). It can be a member however.
What you have is rather inefficient, since it wastes CPU cycles waiting for the next wakeup time. If I were you, I'd rewrite the function using Thread.sleep().
As to why your current code doesn't work, your for loop conditions are off, so the loop is never entered.
To have the timer code run concurrently with whatever other logic you have in your program, you'll need to look into threading.
It sounds like you might want to look into multithreading. If you search SO for this, you will find several good question/answer threads. There are also tutorials elsewhere on the web...
Have a look at Timer or better ScheduledExecutorService. They enable you to execute some action periodically and handle the computations surrounding that.
I am using a while loop with a timer.
The thing is that the timer is not used in every loop.
It is used only the first time. After the first time the statements included inside the loop are executed without the delay that i have set.
How is this even possible since the timer is included inside the while loop.
Any solutions ?
int count = 1;
while (count <= 10) {
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
// Stuff the while loop executes
}
});
}
}, 20000);
count++;
}
The TimerTask kicks off a new Thread and then the loop proceeds as normal.
The execution of the thread does not cause a delay to the execution of the code in your loop.
It's because you're queueing up 10 toasts all to execute in one hour. Each iteration of your loop takes only a fraction of a millisecond or maybe a tad bit more than that. To enqueue them properly, you could do 3600000 * count instead of 3600000 each time.
This is a terrible way to do it though. You should use AlarmManager for stuff like this.
You're scheduling 10 TimerTasks to execute after an hour, at the same time. So all 10 tasks are being executed after 1 hour, which makes it seem like 1 execute since all the Toast messages display at the same time. To schedule tasks at a fixed delay, with the first task starting in 1 hour, use this method:
Timer t = new Timer();
t.schedule(task, 3600000, 3600000);
This will execute until you call t.cancel().
I am using a while loop with a timer.
The thing is that the timer is not used in every loop.
It is used only the first time. After the first time the statements included inside the loop are executed without the delay that i have set.
How is this even possible since the timer is included inside the while loop.
Any solutions ?
int count = 1;
while (count <= 10) {
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
// Stuff the while loop executes
}
});
}
}, 20000);
count++;
}
The TimerTask kicks off a new Thread and then the loop proceeds as normal.
The execution of the thread does not cause a delay to the execution of the code in your loop.
It's because you're queueing up 10 toasts all to execute in one hour. Each iteration of your loop takes only a fraction of a millisecond or maybe a tad bit more than that. To enqueue them properly, you could do 3600000 * count instead of 3600000 each time.
This is a terrible way to do it though. You should use AlarmManager for stuff like this.
You're scheduling 10 TimerTasks to execute after an hour, at the same time. So all 10 tasks are being executed after 1 hour, which makes it seem like 1 execute since all the Toast messages display at the same time. To schedule tasks at a fixed delay, with the first task starting in 1 hour, use this method:
Timer t = new Timer();
t.schedule(task, 3600000, 3600000);
This will execute until you call t.cancel().