I am very new to the android platform thus java so i have a pretty basic question i am trying to make a simple second timer so here is the code i have written. I don't know why but the method run never gets executed:
Timer tmr = new Timer();
tmr.schedule(new TimerTask()
{
#Override
public void run() {
TextView txt = (TextView) findViewById(R.id.txtLoading);
counter++;
txt.setText(counter);
}
}, 1000);
LE : actually it looks like it executing but the GUI doesn't get updated ... why ?
Using Timer like that creates a new Thread, and updating the GUI from a thread which is not the main thread is not a good idea.
A better approach is the one reported in this link: http://developer.android.com/resources/articles/timed-ui-updates.html
Hope it helps!
I guess that is because you are not working in your UI thread. Read about UI threads here.
You might want to consider using AsyncTask that takes care of all the UI thread syncronisation stuff ;)
change your code like this
Timer tmr = new Timer();
tmr.schedule(new TimerTask()
{
#Override
public void run() {
Log.w("this", "is 1");
}
},1000, 1000);
Related
I'm trying to test the use of time in Java to manipulate code. So let's say I have a app with an egg. The egg won't hatch until 60 seconds have passed in the application, what method or class would I use to do this?
The Timer class should do what you are after:
A facility for threads to schedule tasks for future execution in a background thread. Tasks
may be scheduled for one-time execution, or for repeated execution at
regular intervals.
You can take a look at a simple example available here.
You can use timer in a way like this
Timer timer = new Timer();
If you want your code to run multiple times:
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Your logic here
// Your logic will run every 60 second
System.out.println("egg hatched");
}
}, 0, 60000);
If you want it to run only one time
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here
System.out.println("egg hatched");
}
}, 60000);
You can read more about class timer in java here
The easiest old-fashioned single thread approach is
Thread.sleep(60*1000);
System.out.println("egg hatched");
And there is no guaranty that it print exactly after minute
System.currentTimeMillis() returns the current time of the system in milliseconds to your. So you need to create a Thread checking for the current time in a while loop an react to it.
Try run it it a separate scheduled thread;
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
Runnable hatcher = new Runnable() {
#Override
public void run() {
egg.hatch();
}
};
scheduler.schedule(hatcher, 60, TimeUnit.SECONDS);
I'm working on a text adventure game for my Java class, and I'm running into a problem while trying to time a print statement from showing up in the console.
Basically after 45 seconds I would like a print statement to show up, in this case the print statement would be reminding the user that they need to let their virtual dog out...
I also need the timer to reset after the user gives the correct command.
import java.util.Timer;
import java.util.TimerTask;
...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("delayed hello world");
}
}, 45000);
Timer
TimerTask
To cancel the timer, either use a TimerTask variable to remember the task and then call its cancel() method, or use timer.purge(); the latter cancels all tasks on the timer. To schedule the task again, just repeat.
You'll probably want to do more advanced operations in the future, so reading the Timer API docs is a good idea.
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run() {
System.out.println(" let the virtual dog out ");
}
}, 45000);
Try running in a new Thread.
new Thread(new Runnable()
{
public void run()
{
Thread.sleep(45000);
System.out.println("My message");
}
})
.run();
This should work.
Just tell the thread to sleep for 45 seconds, there is a tutorial here:
http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
Tell the main thread to sleep might not be ideal as it will cause your program to basically stop. Use a another thread(need to do a little multi-threading) for timing your output and do a check if the message should be printed after the 45s.
I have a TextArea that I would like to be able to append characters or words to over a period of time. I tried using Thread.sleep() but then quickly realized this was horribly wrong.
I guess in pseudo-pseudocode
textArea.appendText("hey");
mysteryWaitMethod(500);
textArea.appendText("delayed");
JavaFX does have a timer built in - it's called a Timeline. It's simple, straightforward, and provides extra functionality like Swing's Timer class, and, most importantly, executes code on the UI thread.
I don't know much about JavaFX directly, but generally you want things that modify the UI executing on the UI thread. That's what this class does... I'd recommend using it over java.util.Timer (use that for background tasks... not UI ones). When multiple threads try to mess with a UI, bad things tend to happen (which is the reason for these timers).
This post provides a good example of how to use it: https://stackoverflow.com/a/9966213/1515592
Use the javax.swing.Timer
textArea.appendText("hey");
int delay = 500; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
textArea.appendText("delayed");
}
};
Timer t = new Timer(delay, taskPerformer);
t.setRepeats(false);
t.start();
http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html
Or java.util.Timer
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
textArea.appendText("delayed");
}
}, 500);
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html
After creating a session, i want to call a method again & again after a specific time - i.e. 5 sec.
But when i call a method it gives me an error. Here is the sample code.
public class RunFunction extends MainScreen{
public RunFunction()
{
//Call Function again and again after 5 sec
setTitle("Timer");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
BasicEditField b = new BasicEditField("Hello", "");
String a = b.getText();
Dialog.alert("Value " +a);
}
}, 5000);
}
}
I need help related to this. Can you provide any sample code?
From the BlackBerry docs on the Timer class:
A facility for threads to schedule tasks for future execution in a background thread.
So, the first thing to understand is that whatever work you do in the run() method will be run on a background thread. Background threads are not allowed to modify the UI directly. You're probably getting an IllegalStateException by doing that.
Maybe this is just test code, but this code
BasicEditField b = new BasicEditField("Hello", "");
String a = b.getText();
Dialog.alert("Value " +a);
is a little confusing. It creates a BasicEditField, but only uses it to get the String value passed in to it. Just instantiating a field does not add it to a screen. So, you would need to call
add(b);
after this code for the edit field to show. But again, that would be modifying the UI directly. So, in your case, you probably just need to wrap your code with a call to UiApplication#invokeLater():
timer.schedule(new TimerTask() {
public void run() {
// this code executed on background thread -> not UI safe!
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// this code safely executed on UI thread
BasicEditField b = new BasicEditField("Hello", "");
add(b);
String a = b.getText();
Dialog.alert("Value " +a);
}
});
}
}, 5000);
Next, calling Timer#schedule(TimerTask,long) will only schedule your task to run once, after 5000 milliseconds. If you want it to run again and again, use the version of schedule(TimerTask,long,long) that takes three parameters. The last parameter is the amount of time between each call to your timer task's run() method.
This example on Timer and TimerTask java class provides some insights on what you want to do:
http://javaprogramming.language-tutorial.com/2012/02/demonstrate-timer-and-timertask.html
How can I call a method every n seconds?
I want to do a slideshow with Swing and CardLayout and every n seconds
it must show a different image calling a different method
import java.util.*;
class MyTimer extends TimerTask
{
public void run()
{
//change image
}
}
then in your main you can schedule the task:
Timer t = new Timer();
t.schedule(new MyTimer(), 0, 5000);
first number is initial delay, second is the time between calls to run() of your TimerTask: 5000 is 5 seconds.
As BalusC noted usually you dispatch swing changes on AWT event thread. In this simple cause it shouldn't create problems when changing background from an outside thread, in any case you should use
public static void SwingUtilities.invokeLater(Runnable whatToExecute)
to dispatch your change on the right thread.
If you prefer BalusC approach just use an ActionListener:
public void BackgroundChange implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//change bg
}
}
javax.swing.Timer t = new javax.swing.Timer(5000, new BackgroundChange());
They both provide same functionality, but this later one is already prepared to work out together with Swing threads mantaining compatibility and avoiding strange synchronizations issues.
Since you're using Swing, you would like to use javax.swing.Timer for this. Here's a Sun tutorial on the subject.
For any more than trivial animation in Swing app, check out Trident: http://kenai.com/projects/trident/pages/Home