I got timerTask which calls every 500ms. Every time it calls it freeze my ui thread for a moment. My question is how to make it runs in not UI thread?
mTimer.schedule(keeper, 0, 500);
private class PlayerKeeper extends TimerTask {
#Override
public void run() {
new Thread(new Runnable() {
#Override
public void run() {}
});
Related
In java and android world, to run now Thread we execute it like this
Thread tr = new Thread(new Runnable() {
#Override
public void run() {
todo();
}
});
tr.start();
so tr is new Thread, but in android api PerformClick implements Runnable interface and is called normally by execute run method
private static void handleCallback(Message message) {
message.callback.run();
}
callback is PerformClick
private final class PerformClick implements Runnable {
#Override
public void run() {
performClick();
}
}
I am trying understand why for this case it is not new Thread
Thanks
I have an application in Java where I need to schedule a TimerTaskwhich will be executed after 500ms , however if a certain event occurs, I must reset the timer for this task (so that we must wait another 500ms for it to execute). I have a timer declared for the whole class. I use the following code:
public static void main(String[] args) {
if (curr_pck == my_pck) {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
}
}
public static void myTask() {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
//EXECUTE CODE WHICH ISN'T RELEVANT TO THE QUESTION
}
I know that if I use timer.cancel() I can't reuse the timer object, however I thought reinitialising it in the line timer = new Timer() should solve this issue. Is there any way around this?
EXCEPTION on line timer.schedule(new TimerTask() { inside myTask() function:
java.lang.IllegalStateException: Timer already cancelled.
Create a class Timerr with the appropriate methods. Then access it as if it were a normal timer.
public class Timerr
{
private Timer timer;
public Timerr()
{
timer = new Timer();
start();
}
public void start()
{
timer.schedule(new TimerTask()
{
#Override
public void run()
{
System.out.println("hi");
}
}, 500);
}
public void reset()
{
timer.cancel();
timer.purge();
start();
}
}
Create instance
private Timerr timer = new Timerr();
Do your reset
if(condition)
{
timerr.reset();
}
You may want to check out Java's Swing timer. It works somewhat differently and you may have to write an internal class or an actionlistener, but the Swing timer includes .stop() and .restart(), which seem like they would work better in your application.
I want to print this line:
System.out.println(Runtime.getRuntime().freeMemory());
every second. How to do it?
public class Hilo implements Runnable{
Thread t;
String nombre;
public Hilo() {
t = new Thread(this,"Hilo1");
t.start();
}
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}
Use a java.util.Timer object.
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.
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1000);
Another way to do it
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1, TimeUnit.SECONDS);
ses.shutdown();
Differences between java.util.timer and ScheduledExecutorService
ScheduledThreadPoolExecutor are not sensitive to changes in the system clock but Timer is.
Timer has only one execution thread, so long-running task can delay other tasks.
ScheduledThreadPoolExecutor can be configured with any number of threads
By using below code you can print that want after every second
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1000);
}
How can I use a timer to delay a calling a method once by a random time?
if(getDropPickup())
{
Timer timer = new Timer(getDelayTime(), new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
collectItems();
}
});
timer.setRepeats(false);
timer.start();
}
When I try to do something like this I have problems with the timer constructor being undefined. What is the best way to call a method after an amount of time without delaying the main thread?
You can create a Thread which uses Thread.sleep() so you wont block your main thread
while using the sleep method.
sample:
if(getDropPickup())
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
int delay = getDelayTime();
Thread.sleep(delay);
collectItems();
}
});
t.start();
}
How can this be done in android?
public final Timer timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do task here
}
});
I need to be able to call timer.start(); from the Activity that timer is in.
In most cases it is much better to use a Handler instead of Timer. Handler is capable of sending delayed messages. Benefits of using Handler are:
it runs on the main (UI) thread -> can access Views (unlike the
Timer, which cannot dircetly access Views)
You can remove pending delayed messages if you want
Less code
Example:
class MyActivity extends Activity {
private static final int DISPLAY_DATA = 1;
// this handler will receive a delayed message
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Do task here
if (msg.what == DISPLAY_DATA) displayData();
}
};
#Override
void onCreate(Bundle b) {
//this will post a message to the mHandler, which mHandler will get
//after 5 seconds
mHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 5000);
}
}
Android has a nice CountDownTimer class, too
Try something like this:
// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {
#Override
public void run() {
// ...
}
};
// new timer
Timer timer = new Timer();
// schedule timer
timer.schedule(myTimerTask, delayInMs);
If you want task to be done in activity's main thread, modify it like this:
// get a handler (call from main thread)
final Handler handler = new Handler();
// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {
#Override
public void run() {
// post a runnable to the handler
handler.post(new Runnable() {
#Override
public void run() {
// ...
}
});
}
};
// new timer
Timer timer = new Timer();
// schedule timer
timer.schedule(myTimerTask, delayInMs);
I have answered this in another question.
I would avoid the TimerTask, if you fire a lot of them off, they are not only difficult to manage but bad for performance.
I would recommend a Handler for pretty much any Time based task these days.
See Timer application