Timer won't stop when there is a Thread.sleep inside Java - java

Hello i have this code to display images with javafx
public void CantaCarta() throws InterruptedException {
startGame.setDisable(true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
SwingUtilities.invokeLater(() -> {
for (int x=1; x<55;x++){
Image image = new Image(getClass().getResource("imgs/"+JuegoLoto.Muestra(x-1)+".jpg").toString(), true);
cantada.setImage(image);
if (x >= 54) {
System.out.print("Termina");
timer.cancel();
} else {
System.out.print(" "+x+" ");
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
}
}
}
});
}
}, 0, 1000);
}
The images will displa correctly but when the image number 54 is in the screen it will be back to 1 in a loop all because of this
Thread.sleep(200);
How can i solve this? i want to delay the time beetween images

This doesn't begin to make sense.
You're scheduling a timer task to run every 1000 milliseconds.
The task has 54 internal iterations which each display an image and in all cases except the last sleep for 200ms.
Total time so far 10600 milliseconds plus however long it takes to display the images
The timer will reschedule the task after 1000ms of that: meanwhile
the task will cancel the timer on the last iteration.
So you will get:
53 images and 53 200ms sleeps
a restart of the task after about 10% of that is complete
a 54th image
the timer gets cancelled.
So you get about ten or eleven iterations of the task, mostly in parallel.
I suggest you:
schedule the task at 200ms intervals, have it display the next sequential image every time it is invok d, wrapping around to the beginning or cancelling the timer or whatever you want when it gets to the last image, and
get rid of the internal loop.

Related

Run an if-statement for a certain amount of time

I want to check if an int value is higher than 20 for a certain amount of 15 minutes, if that int value stays higher than 20 in those 15 minutes, code will executed
I didn't understand the difference between a Handler and a Runnable, how to use them, What do they do...
My question is:
How can I run an if statement for a certain time using a Runnable/Handler
This is the if statement which I want to be checked for 15 mins,
if(Speed > 20){
// Code that will run after 15 mins IF the speed is higher than 20 for all that time
}
add this, this timer will execute after 1 sec you can add your time you want and put your if statement inside run function
private Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
Try using below code. It uses a while loop which will keep of looping for-ever until two condition are met
1) i becomes greater than 20
2) flag is set to false
For each iteration, it will sleep for 1 minute
public static void main(String[] args) {
int i = 0;
boolean flag = true;
try {
while (i < 20 && flag) {
TimeUnit.MINUTES.sleep(1);
// Expecting some logic to increment the value of i
// Or change the flag value of this to exit the while loop
}
} catch (Exception exp) {
exp.printStackTrace();
}
}

How to get time left in a java.util.Timer?

How can I get the time left in a util.Timer?
What I want to do is to add a progressbar that displays time left until the timer starts over.
This is what I've got this far:
int seconds = 8;
java.util.Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run(){
// Do something
// Add a progressbar that displays time left until the timer "starts over".
},0,(long) (seconds*1000));
You would need a second timer to refresh the gui in a specific interval.
Another way to achieve this, would be to activate a single timer every second and update the counting in the ui. If the time is up, call your specific action.
A simple expample with console output only:
TimerTask task = new TimerTask()
{
int seconds = 8;
int i = 0;
#Override
public void run()
{
i++;
if(i % seconds == 0)
System.out.println("Timer action!");
else
System.out.println("Time left:" + (seconds - (i %seconds)) );
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 1000);
It's output would be:
Time left:7
Time left:6
Time left:5
Time left:4
Time left:3
Time left:2
Time left:1
Timer action!
Time left:7
Time left:6
Time left:5
Time left:4
Time left:3
Time left:2
Time left:1
Timer action!
Time left:7
Time left:6
...
Then simply change the System.out's with your code to update the progress bar. Remember: java.util.Timer starts its own Thread. Swing is not thread safe, so you need to put every gui changing code into SwingUtilities.invokeLater()!
If you're not doing any long running tasks, every time your timer reachs the 8 seconds mark, you may want to use javax.swing.Timer directly. It uses the EDT and not its own Thread, so you don't need to synchronize your calls to Swing components with SwingUtilities.invokeLater().
Also see:
javax.swing.Timer vs java.util.Timer inside of a Swing application
All you need to do is declare a long variable timeleft in your MainActivity.
long timeleft;
Then, when you create a new Timer, set the "onTick" override to update the timeleft variable each "onTick" (which in the following example is 1000 milliseconds )
timer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisecondsUntilFinished) {
timeleft = millisecondsUntilFinished;
}
}
Your app can access then the variable timeleft every time you need to check how much time is left.

Java timer 100 times per second

I'd like to run some method 100 times per second.
What I got is this:
Timer timer = new Timer(0, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
time+= 0.001;
System.out.println(time);
repaint();
}
});
From the output it is clear that timer is faster than it should be. Also it is taking toll on cpu, so i doubt this is right way to do this. If i set new Timer(1, new ActionListener() and time+= 0.01; then it is slower than it should be.
Can anyone help me out with this? How do i perform task 100 times per second?
EDIT:
change to:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
time += 0.01;
System.out.println(time);
repaint();
}
}, 1, 1);
Not sure if its netbeans but output time is waaay of. Its either to slow or to fast. for example output:
57.07999999999721
57.08999999999721
57.09999999999721
57.10999999999721
BUILD STOPPED (total time: 24 seconds)
5.699999999999923
5.709999999999923
5.7199999999999225
5.729999999999922
5.739999999999922
BUILD STOPPED (total time: 8 seconds)
EDIT2:
Changed to timer.scheduleAtFixedRate and it works fine now. THnx #GeorgeG
You can use Timer.scheduleAtFixedRate and run it every 0.01 seconds.
You can use Thread.sleep(10L). This will sleep thread for 10ms. so it'll execute 100 times per second
You can call Thread.sleep() to the slow the rate of execution.
Try this:
int i = 100;
while (i-- > 0) {
myMethod();
try { Thread.sleep(10); } catch (Exception e) {}
}

Java - Android Programming - Loop Fail [duplicate]

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().

Java / Android Programming - Loop FAIL

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().

Categories