What is wrong with my event timer loop thing? - java

I have a timer set up that should run code every 10th of a second, but instead it seems to run the desired code only once. I cannot figure out what I am doing wrong. :{
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
System.out.println("it only prints this once");
}
}, 100, 100000);
Thanks in advance for your help.

The last two arguments to scheduleAtFixedRate seem odd. The first one is always 0 (which is not a problem; just means that there's no delay before the first execution). The second is set to 2 minutes, not 0.1 second. The argument is supposed to be the rate in milliseconds. For 0.1 second, you should use 100, not 2*60*1000.
Try this:
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
System.out.println("it only prints this once");
}
}, 100, 100);

Related

"runOnUIThread" incrementally running everytime I go back to the activity

I have a timer which runs on the activity's OnCreate method as shown below. When run, the timer increments as it should. Showing:
00:00,
00:01,
00:02,
etc.
final Timer timer = new Timer();
final TimerTask timerTask = new TimerTask(){
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String timer = sdf.format(new Date(counter * 1000L));
timerText.setText(timer);
counter++;
}
});
}};
timer.schedule(timerTask, 0, 1000);
However, when I revisit the activity, the timer's interval increases. If I revisit it the first time, the interval becomes 2 i.e.
00:00,
00:02,
00:04,
etc.
Revisiting it again makes the interval 3 i.e.
00:00,
00:03,
00:06,
etc.
And the intervals keep incrementing.
I deduced the runOnUIThread method is being run n times, where n is the number of times onCreate has been accessed, but I don't really know what to do about it.
Use the Timer constructor that specifies it to be a daemon new Timer(true) so that if it exits the timer thread exits too.
Also consider cancelling the timer before exiting on onDestroy or onPause for example.

Java Clock Synchronizing

I have to show multiple clocks in screen from different places like New Delhi, Hong Kong, Frankfurt, Washington, etc. And these times are changing like any other real clock but as Time-Left to a fixed date-time and they are added to the screen at different moments as the user adds them. For example:
New Delhi 1d 4h 20 min 5s
Hong Kong 9h 2min 55s
Washington 22min 3s
...
I have a Class which makes all the calculations to get those times in that format. The problem comes when these times are shown on screen. How do I make them to update their time at the same time? So all the changes in the seconds are shown at the same time. I know it won't be theoretically at the same time, but the most close to it. This is the timer I am using:
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask()
{
public void run() {
Platform.runLater(new Runnable() {
#Override
public void run() {
label[id].setText(getTimeLeft(id));
}
});
}
},
0, // run first occurrence immediately
1000); // run every seconds
Also, some of them freeze eventually. Does any body knows why?
How do I make them to update their time at the same time? So all the changes in the seconds are shown at the same time. I know it won't be theoretically at the same time, but the most close to it. This is the timer I am using:
Instead of using separate Timers for each label, use a single Timer for ALL the labels
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask()
{
public void run() {
Platform.runLater(new Runnable() {
#Override
public void run() {
for (int id = 0; id < label.length; id++) {
label[id].setText(getTimeLeft(id));
}
}
});
}
},
0, // run first occurrence immediately
1000); // run every seconds
This will reduce the overhead of resources on you system (one timer instead of n times), possible event queue spamming as multiple timers trigger simultaneously and allow the times to "seem" to update at the same time, as they are all updated within the event queue, so they won't update until the next paint cycle, which won't happen until you exit the run block...
You could also make use Timeline, which would reduce the need for Platform.runLater, see How to update the label box every 2 seconds in java fx? for an example.

Interval when using TimerTask in conjunction with Timer is not working

I am using timer.schedule(minuteTask, 0, 1000*60) to generate a new color at regular intervals. As you can see by the gif below that I recorded, the interval does not seem to be working.
Timer timer = new Timer ();
TimerTask minuteTask = new TimerTask() {
#Override
public void run () {
java.util.Random random = new java.util.Random();
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
}
};
timer.schedule(minuteTask, 0, 1000*60);
Any idea on how to fix this?
Use this
new Timer().scheduleAtFixedRate(
new TimerTask() {
#Override
public void run() {
//put UR code herr
}
}, 0, 1000);
Hi I think you should use the scheduleAtFixedRate(..) function of Timer. This will help you to change the color in given time interval.
A simple schedule() method will execute at once while scheduleAtFixedRate() method takes and extra parameter which is for repetition of the task again & again on specific time interval.
Look at below code snippet:
Timer timer = new Timer();
timer.schedule( new performClass(), 30000 );
This is going to perform once after the 30 Second Time Period Interval is over. A kind of timeoput-action.
Timer timer = new Timer();
//timer.scheduleAtFixedRate(task, delay, period);
timer.scheduleAtFixedRate( new performClass(), 1000, 30000 );
This is going to start after 1 second and will repeat on every 30 seconds time interval.

In Java, how do I execute code every X seconds?

I'm making a really simple snake game, and I have an object called Apple which I want to move to a random position every X seconds. So my question is, what is the easiest way to execute this code every X seconds?
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Thanks.
Edit:
Well do have a timer already like this:
Timer t = new Timer(10,this);
t.start();
What it does is draw my graphic elements when the game is started, it runs this code:
#Override
public void actionPerformed(ActionEvent arg0) {
Graphics g = this.getGraphics();
Graphics e = this.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
e.fillRect(0, 0, this.getWidth(), this.getHeight());
ep.drawApple(e);
se.drawMe(g);
I would use an executor
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable toRun = new Runnable() {
public void run() {
System.out.println("your code...");
}
};
ScheduledFuture<?> handle = scheduler.scheduleAtFixedRate(toRun, 1, 1, TimeUnit.SECONDS);
Use a timer:
Timer timer = new Timer();
int begin = 1000; //timer starts after 1 second.
int timeinterval = 10 * 1000; //timer executes every 10 seconds.
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//This code is executed at every interval defined by timeinterval (eg 10 seconds)
//And starts after x milliseconds defined by begin.
}
},begin, timeinterval);
Documentation: Oracle documentation Timer
Simplest thing is to use sleep.
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Thread.sleep(1000);
Run the above code in loop.
This will give you an approximate(may not be exact) one second delay.
You should have some sort of game loop which is responsible for processing the game. You can trigger code to be executed within this loop every x milliseconds like so:
while(gameLoopRunning) {
if((System.currentTimeMillis() - lastExecution) >= 1000) {
// Code to move apple goes here.
lastExecution = System.currentTimeMillis();
}
}
In this example, the condition in the if statement would evaluate to true every 1000 milliseconds.

With each successive call to this `timerMethod` , timerInt's value increases faster than before

I am working on an app, which gets a sort of restart with an event. On the first run, the timer works perfect (1sec = 1 increment). but, on next run (1sec = 2 increment) on third run (1sec = 4 increment) and so on...
I think there is something wrong with the new TimerTask object being created. but, dunno how to handle it. any suggestion or alternate ?
CODE SNIPPET:
Timer t = new Timer();
void timerMethod()
{
t.schedule(new TimerTask() {
public void run() {
timerInt++;
//TODO bug in timer in consecutive runs. To confirm, see log
Log.d("timer", "timer " + timerInt);
/* runOnUiThread(new Runnable() {
#Override
public void run() {
timerDisplayPanel.setText( timerInt + " Sec");
}
});*/
}
}, 1000, 1000);
}
It sounds like you're calling timerMethod() multiple times.
When you've called it three times, you've got three timer tasks scheduled - so they'll all fire each second, and all increment timerInt. You either need to not call it multiple times, or cancel the existing timer tasks before adding more.
If that's not the case, please provide a short but complete program to show what's happening. The context is fairly vague at the moment.
The snippet you provided is working properly
1 sec 1 increment
2 sec 2 increment
3 sec 3 increment
etc
So probably the problem is somewhere else in your code.

Categories

Resources