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) {}
}
Related
I have the follow problem:
i'm writing an chat bot in java and i want to call a method even x minutes.
So i read an "Timer.Schedule" is what i need. So i write the following method:
public function timerMethod()
{
int time = 10;
...
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 1000 * 60 * time // 1MSec * 1Sec * xMin
);
}
At the beginning the loop works fine but after a few hours (i think it's after 10-15 hours) the loop dont work anymore...
I dont know why i dont work and dont get any error message :(
Can someone help me pleace???
So you want code to run for x minutes, correct?
If so, convert the time you want the code to run for into milliseconds like this : 1 minute = 60000 ms. There is a method called System.currentTimeMillis(), this will return a value of miliseconds from the EPOCH date (Jan 1, 1970).
You can use a while loop like this:
`
int msTime = 60000; //1 Minute = 60000 MS
int doUntil = ms + System.currentTimeMillis(); //1 minute
while(System.currentTimeMillis() != doUntil)
{
//Code here
System.out.println(¨Hello World¨); //This will print Ḧello World for 60000ms
}
Mmm well first you can stop instantiating multiple times the java.util.Timer() variable. You only need one as an attribute of the class. The timerTask is the only one there that should be reinstantiated.
private Timer timer = new Timer();
Now, surround your code inside the run function with try/catch:
public void run() {
try {
timerMethod();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
Are you calling that timerMethod just once? You can add to this code some prints too in order to check whenever you reschedule your function and when you run your method.
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.
I'm trying to make a stopwatch in Java and don't know how to pause and continue my timer. Here is what I have done so far.
startButton.addActionListener(this);
stopButton.addActionListener(this);
pauseButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
Calendar aCalendar = Calendar.getInstance();
if (e.getSource() == startButton){
start = aCalendar.getTimeInMillis();
startButton.setBackground(Color.GREEN);
stopButton.setBackground(null);
pauseButton.setBackground(null);
} else if (e.getSource() == stopButton) {
stopButton.setBackground(Color.RED);
startButton.setBackground(null);
pauseButton.setBackground(null);
aJLabel.setText("Elapsed time is: " +
(double) (aCalendar.getTimeInMillis() - start) / 1000 );
} else if (e.getSource() == pauseButton) {
pauseButton.setBackground(Color.YELLOW);
stopButton.setBackground(null);
startButton.setBackground(null);
}
}
As you can see, I've only changed the colors for my pause button. I don't really know how to pause the thread by having the user click on the button. All examples I've found of thread.sleep() were with a specific time.
You can use the swing.Timer (not util.Timer) like this:
int interval = 100; // set milliseconds for each loop
Timer timer = new Timer(interval, (evt) -> repeatingProccess());
// create the method repeatingProccess() with your
// code that makes the clock tick
startButton.addActionListener(e -> timer.start());
stopButton.addActionListener( e -> {
timer.stop();
// here refresh your clock with some code...
};
pauseButton.addActionListener(e -> timer.stop());
You write a method called repeatingProccess() and it works in its own thread again and again every interval milliseconds. For a clock that counts seconds you can do this:
int interval = 1000;
int seconds = 0;
public void repeatingProccess() {
seconds++ ;
}
note:
The second will not be exactly 1000 milliseconds but around 1001 because of the time needed to run seconds++ but you can fix that as well by getting System time before and after and substracting the difference from your clock. You should use the Calendar API for this.
I'm working on a school project in Java and need to figure out how to create a timer.
The timer I'm trying to build is supposed to count down from 60 seconds.
You can use:
int i = 60;
while (i>0){
System.out.println("Remaining: "i+" seconds");
try {
i--;
Thread.sleep(1000L); // 1000L = 1000ms = 1 second
}
catch (InterruptedException e) {
//I don't think you need to do anything for your particular problem
}
}
Or something like that
EDIT, i Know this is not the best option, otherwise you should create a new class:
Correct way to do this:
public class MyTimer implements java.lang.Runnable{
#Override
public void run() {
this.runTimer();
}
public void runTimer(){
int i = 60;
while (i>0){
System.out.println("Remaining: "+i+" seconds");
try {
i--;
Thread.sleep(1000L); // 1000L = 1000ms = 1 second
}
catch (InterruptedException e) {
//I don't think you need to do anything for your particular problem
}
}
}
}
Then you do in your code:
Thread thread = new Thread(MyTimer);
Since you didn't provide specifics, this would work if you don't need it to be perfectly accurate.
for (int seconds=60 ; seconds-- ; seconds >= 0)
{
System.out.println(seconds);
Thread.sleep(1000);
}
Look into Timer, ActionListener, Thread
There are many ways to do this. Consider using a sleep function and have it sleep 1 second between each iteration and display the seconds left.
It is simple to countdown with Java. Lets say you want to countdown 10 min so Try this.
int second=60,minute=10;
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
second--;
// put second and minute where you want, or print..
if (second<0) {
second=59;
minute--; // countdown one minute.
if (minute<0) {
minute=9;
}
}
}
};
new Timer(delay, taskPerformer).start();
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().