How to set a delay on a method - java

When i currently call my method
public void flip() {
Image change = new ImageIcon(this.getClass().getResource(imageName[0])).getImage();
ImageIcon card = new ImageIcon(change);
imagelbl.setIcon(card);
}
Currently when the method is called the code runs and the method works. This is perfect however i need there to be a delay of 1 second before the method runs.
I have tried using setTimeout() but i was unsuccessful. How would i get this method to have a 1 sec delay before running?

Use the Timer class for timing.
public void callerMethod() {
System.out.println("Start");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
delayedMethod();
}
}, 1000);
}
public void delayedMethod() {
System.out.println("Test");
}

Use Thread.sleep(1000) as the first line in flip() method.

Related

How to submit a TimerTask to another Timer when it 's running

In a run method of a TimerTask object, How can I submit the timerTask itself to another Timer.
When the timerTask is running, I should do a judge and decide whether it can do some work. If it not meet the condition, I should cancel it and put it to another Timer.
Code of my TimerTask is like this:
#Override
public void run() {
try {
if (flag) {
// do something
} else {
new Timer().schedule(this, 1000 * 60);
}
} catch (Exception e) {
e.printStackTrace();
}
Will it work?
You should only use one Timer and then monitor the condition from external, for example from a Thread, a Runnable or another Timer. Then stop, cancel, re-assign, start the timer as necessary from your external monitor.
Here's a TimerTask:
public class OurTask extends TimerTask {
#Override
public void run() {
// Do something
}
}
And here's the monitor:
public Monitor implements Runnable() {
private Timer mTimerToMonitor;
public Monitor(Timer timerToMonitor) {
this.mTimerToMonitor = timerToMonitor;
}
#Override
public void run() {
while (true) {
if (!flag) {
// Cancel the timer and start a new
this.mTimerToMonitor.cancel();
this.mTimerToMonitor = new Timer();
this.mTimerToMonitor.schedule(...);
}
// Wait a second
Thread.sleep(1000);
}
}
}
Note that in practice your Monitor should also be able to get canceled from outside, currently it runs infinitely.
And this is how you could call it:
Timer timer = new Timer();
timer.schedule(new OurTask(), ...);
Thread monitorThread = new Thread(new Monitor(timer));
monitorThread.start();
Also note that instead of using Runnable, Timer and Thread it could be worth taking a look into the new Java 8 stuff, especially the interface Future and classes implementing it.

Count up timer on Android?

I've been looking for a way to create a timer that counts up in the format of mm:ss:SS and cannot for the life of me find a way of doing it. I had a timer running through a Handler and a Runnable but the timing was off and it took around 2.5 seconds to do a "second". I'll also need this timer be able to countdown too!
Can anyone give me any resources or code snippets to research on this as it is a big part of the app I'm coding.
Here's a bit of the code that I was using
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
/* do what you need to do */
testMethod();
/* and here comes the "trick" */
handler.postDelayed(this, 10);
}
};
public void testMethod()
{
// Log.d("Testing", "Test");
final TextView timeLabel = (TextView)findViewById(R.id.timeString);
count++;
seconds = (int)(count / 100);
final String str = ""+count;
runOnUiThread(new Runnable() {
public void run() {
timeLabel.setText("" + seconds);
// Log.d("Time", "" + count);
}
});
}
Ta!
Make small custom class by extending CountDownTimer class and then add integer or long type and then increment it, since each tick is 1 second (integer) in this case
public class TimeCounter extends CountDownTimer {
// this is my seconds up counter
int countUpTimer;
public TimeCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
countUpTimer=0;
}
#Override
public void onTick(long l) {
//since each tick interval is one second
// just add 1 to this each time
myTextView.setText("Seconds:"+countUpTimer);
countUpTimer = countUpTimer+1;
}
#Override
public void onFinish() {
//reset counter to 0 if you want
countUpTimer=0;
}
}
TimeCounter timer = new TimeCounter(whenToStopInSeconds*1000, 1000);
This should get you started, in your case use long instead integer
countUpTimer = countUpTimer+1000 countUpTimer type and do time parsing as suits you
Rather than using the Handler, I'd recommend using the java.util.Timer and the java.util.TimerTask APIs. Use the Timer's void scheduleAtFixedRate() method which basically executes tasks after a fixed interval of time. The Handler's method most likely uses a fixed-delay execution.
Timer's Documentation
TimerTask's Documentation

Java timer.cancel() not stopping timer

I'm a novice at Java, and I've been trying to use java.util.timer to reset an existing timer after taking the right command input.
However, I've been unable to cancel the timertask properly, so the timer thread runs multiple instances of the timertask if the method is called multiple times. Any help would be appreciated.
Edit: I've changed the location of new Timer(), but it doesn't seem to have fixed it.
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
public static void main (String[] args) {
Timer timer = new Timer();
while (true) {
//BufferedReader to read input
//Something
if (input[0].equals("r")) {
time t = new time();
time.RestartTimer();
}
}
}
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
This is happening because you are creating a new instance of time class (time t = new time(); ) inside the while loop. Instead do this :
public static void main (String[] args) {
time t = new time(); // create an instance of time class
while (true) {
//Something
if (input[0].equals("r")) {
// call RestartTimer on the same in
t.RestartTimer();
}
}
}
Also inside RestartTimer() function you are creating new instance of Timer. Change it as follows :
public void RestartTimer() {
ttimer.cancel();
timer.cancel();
timer = new Timer();
TimerTask ttimer = new TimerTask() {
public void run() {
System.out.println("ping");
}
};
timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}
time.RestartTimer(); statement won't be called until and unless either you change the modifier of method or call this method by using static object in main method. I think this is the only reason that your timer is not getting update.

Does scheduling a java.util.timer exit that timer's timerTask method?

Suppose I have a class that looks something like this:
import javax.swing.*;
import java.util.*;
public class MyClass extends JFrame
{
private java.util.Timer timer = new java.util.Timer();
...
private class MyTimerTask extends TimerTask
{
#Override
public void run()
{
doStuff();
if (conditionIsMet())
{
timer.schedule(new MyTimerTask(), 1000);
}
else
{
timer.schedule(new MyTimerTask(), 500);
}
}
}
}
Now I have always thought of the run method of a TimerTask somewhat like a loop. It runs once, then, if you want to run it again you can do so by calling schedule. So my question is: When I call timer.schedule() does it execute any other code in the TimerTask or does it act as if I used break in a loop? If I wrote the method like this instead:
#Override
public void run()
{
doStuff();
if (conditionIsMet())
{
timer.schedule(new MyTimerTask(), 1000); // method wouldn't end after this call
}
timer.schedule(new MyTimerTask(), 500);
}
Would it function the same?
Scheduling a timer task is just a method call; it does not cause the current execution of the timer task's run() method to end, so no, the two code examples do not function the same. It's better practice to use the first of your two code examples, scheduling the task only once in the run method.

Blackberry timer not firing TimerTask

I am trying to use a time that updates a label every second (so it shows a countdown) but it only
appears to be "ticking" once and I can't work out what I'm doing wrong!
public class Puzzle extends UiApplication {
public static void main(String[] args) {
Puzzle puzzle = new Puzzle();
puzzle.enterEventDispatcher();
}
public Puzzle() {
pushScreen(new PuzzleScreen());
}
}
class PuzzleScreen extends MainScreen {
LabelField timerLabel;
Timer timer;
public static int COUNT = 0;
public PuzzleScreen() {
//set up puzzle
VerticalFieldManager vfm = new VerticalFieldManager();
add(vfm);
timerLabel = new LabelField();
timerLabel.setText("00:20");
vfm.add(timerLabel);
StartTimer();
}
void StartTimer() {
timer = new Timer();
timer.schedule(new TimerTick(), 1000);
}
private class TimerTick extends TimerTask {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
timerLabel.setText((COUNT++) + "");
}
});
}
}
Can anyone see what I am doing wrong..? All that happens is my label get's set to "0" and then doesn't change. I have put a breakpoint on the run in the timer tick class but I don't see it firing!
Bex
You'll need to change your Timer's schedule() call to
timer.schedule(new TimerTick(), 0, 1000);
The way you're calling it right now is saying to run it once after a second delay. This way says to run it now and every second. You probably want to use
timer.scheduleAtFixedRate(new TimerTick(), 0, 1000);
though, because it will make sure that on average your TimerTask is ran every second rather than with a normal schedule() call that says it will try waiting a second then executing, but it could fall behind if something slows it down. If scheduleAtFixedRate() is delayed, it will make multiple calls quicker than on the 1 second delay so it can "catch up." Take a look at http://www.blackberry.com/developers/docs/5.0.0api/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask,%20long,%20long) for a more detailed explanation.

Categories

Resources