Let's say I have the following (ref page):
public class TimerExample implements EntryPoint, ClickHandler {
public void onModuleLoad() {
Button b = new Button("Click and wait 5 seconds");
b.addClickHandler(this);
RootPanel.get().add(b);
}
public void onClick(ClickEvent event) {
// Create a new timer that calls Window.alert().
Timer t = new Timer() {
#Override
public void run() {
Window.alert("Nifty, eh?");
}
};
// Schedule the timer to run once in 5 seconds.
t.schedule(5000);
}
}
How come the Timer is still around after the method onClick exits? Shouldn't the automatic local variables be garbage collected?
Does this have to do with the fact we are talking about a HTML timer and thus the object exists outside of the automatic local variables?
The Timer.schedule(int delayMillis) method adds itself (the instance of Timer) to a List of Timers (source code from 2.5.0-rc1):
/**
* Schedules a timer to elapse in the future.
*
* #param delayMillis how long to wait before the timer elapses, in
* milliseconds
*/
public void schedule(int delayMillis) {
if (delayMillis < 0) {
throw new IllegalArgumentException("must be non-negative");
}
cancel();
isRepeating = false;
timerId = createTimeout(this, delayMillis);
timers.add(this); // <-- Adds itself to a static ArrayList<Timer> here
}
From comment by #veer explaining the scheduler thread:
The timer is going to be handled by a scheduler thread that holds a
reference to the Timer and thus righfully prevents it from being
garbage collected.
Related
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.
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
Can anyone tell me if this is a safe thing to do? I run a countdown timer (CountDownTimer) and when the timer reaches zero it must start again, counting down for, for example, a longer time. To do this I call
timer = new TableCount(nextTime * 1000, 100);
within the onFinish() method.
It runs without problems, but I'm concerned it may cause a memory leak. Should I rather have the timer fire some kind of notification that it is done? Here are the important bits from the activity code:
public class TableActivity extends Activity {
TableCount timer; // the count down timer
protected int nextTime;
...
// somewhere I call this - user clicked the "start" button
timer = new TableCount(nextTime * 1000, 100);
nextTime += 100; // for example
...
public class TableCount extends CountDownTimer
{
public void onFinish() {
... // check if number of iterations has been reached, else:
// start counting down from the next value
timer = new TableCount(nextTime * 1000, 100);
nextTime += 100; // for example
}
}
You will not leak memory since you are simply changing the reference of your single declaration of TableCount to a new timer which implicitly dereferences the previous object.
Even if you did something bizarre like creating a new timer each run and adding it to an array (for example) you would still not leak. You might eventually run out of memory but that's not the same as leaking since when the activity is finished(), and assuming that you are not holding a static reference somewhere else, then the memory is freed and eligible for garbage collection.
However, why not just reuse the existing timer and use schedule() to run it again?
do not need to initialize timer again....
try this...
int temp=nexttime;
public class TableCount extends CountDownTimer
{
public void onFinish() {
nexttime=temp;
timer.start();
}
}
public class ServiceCount extends CountDownTimer
{
public ServiceCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
count = new ServiceCount((long) (1 * 60 * 1000), 1000); // 1 minute
count.start();
}
#Override
public void onTick(long millisUntilFinished)
{
Log.d("timer", "" + millisUntilFinished / 1000);
}
}
ServiceCount count = new ServiceCount((long) (1 * 60 * 1000), 1000); // 1 minute
count.start();
I have this java code using Threads to calculate the time elapsed once the start button is hit till the stop button is not hit.
I want to do this using Threads only
import javax.swing.*;
import java.awt.event.*;
// This will count the elapsed time between running time of two threads.
class ThreadGame {
JButton button;
MyAction my_action;
public static void main(String[] args) {
ThreadGame tg = new ThreadGame();
}
public ThreadGame() {
JFrame frame = new JFrame("Calculate time - Game");
button = new JButton("Start");
button.addActionListener(new MyAction());
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class MyAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = (String) e.getActionCommand();
final Timer timer = new Timer();
if (text.equals("Start")) {
button.setText("Stop");
Thread start_time = new Thread() {
public void run() {
timer.startTime();
}
};
start_time.start();
try {
start_time.join();
} catch (Exception e1) {
}
} else {
Thread stop_time = new Thread() {
public void run() {
timer.stopTime();
}
};
Thread get_time = new Thread() {
public void run() {
timer.getElapsedTime();
System.out.println(timer.elapsed);
}
};
stop_time.start();
try {
stop_time.join();
} catch (Exception e2) {
}
get_time.start();
button.setText("Start");
}
}
}
class Timer {
public double startTime = 0.0;
public double stopTime = 0.0;
public boolean running = false;
public double elapsed = 0.0;
public void startTime() {
this.startTime = System.nanoTime();
this.running = true;
}
public void stopTime() {
this.stopTime = System.nanoTime();
this.running = false;
}
// Elasped time in seconds
public double getElapsedTime() {
// double elapsed;
if (running) {
elapsed = ((System.nanoTime() - startTime) / 1000);
} else {
elapsed = ((stopTime - startTime) / 1000);
}
return elapsed;
}
}
}
EDIT: I have understand the problem: timer scope was the problem.
EDIT 2: Ok, it looks like I have to use suspend and resume in one thread only.
The problem is that the start button press is starting a different Timer object than the stop-button button press is stopping because the Timer object is created every time when the actionPerformed(...) method is called.
The Timer needs to be a field in your MyAction class. You also don't need all of the thread start/joins because the Timer object is very simple and fast.
Really, you can just use a startTimeMillis long field instead of a timer. Something like:
class MyAction implements ActionListener {
private long startTimeMillis;
public void actionPerformed(ActionEvent e) {
String text = (String) e.getActionCommand();
if (text.equals("Start")) {
startTimeMillis = System.currentTimeMillis();
...
} else {
System.out.println(System.currentTimeMillis() - startTimeMillis);
}
}
}
Your problem is caused by the scope of timer. This should be a private instance variable, not a local method variable. Further, wrapping calls to startTime and endTime in a thread's run method isn't gaining you anything, because these are incredibly short-lived calls. But that's not the real problem here.
There's no reason to be running Timer in its own thread. That is, without using a specialized real-time operating system, using threads to solve the problem of measuring the duration between two events is just plain wrong.
You might think that you could create a thread with a loop that increments a msec variable after a Thread.sleep(1). Don't do this! This kind of timing is also just plain wrong. Your computer uses a preemptive multitasking model which means there's no guarantee that your thread will execute on a regular interval. That is, there is nothing requiring that Thread.sleep(1) will sleep for some maximum duration. The guarantee is that your thread will sleep for a minimum of 1ms. This means there's no way to determine clock error if you're managing a clock yourself in software, and this error is not insignificant. Just don't do it!! Time should always be measured by your operating system, preferably using an interrupt-based timer (which is how System.nanoTime works on most, if not all platforms).
Instead of using a thread, just call your startTime and stopTime methods directly from your original thread.
Try this:
class ThreadGame {
JButton button;
MyAction my_action;
private final Timer timer = new Timer();
public static void main(String[] args) {
ThreadGame tg = new ThreadGame();
}
public ThreadGame() {
JFrame frame = new JFrame("Calculate time - Game");
button = new JButton("Start");
button.addActionListener(new MyAction());
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class MyAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = (String) e.getActionCommand();
if (text.equals("Start")) {
timer.startTime();
button.setText("Stop");
} else {
timer.stopTime();
button.setText("Start");
}
}
}
class Timer {
public double startTime = 0.0;
public double stopTime = 0.0;
public boolean running = false;
public double elapsed = 0.0;
public void startTime() {
this.startTime = System.nanoTime();
this.running = true;
}
public void stopTime() {
this.stopTime = System.nanoTime();
this.running = false;
}
// Elasped time in seconds
public double getElapsedTime() {
return (this.startTime-this.stopTime)*1000000000.0;
}
}
}
If you want to learn how to use threads, try writing an application that solves a problem for which threads are a good fit. For example, write a small Swing application that lets you download a file from the web. As the file is downloading, update a progress bar in your UI. The download should happen in a worker thread separately from the UI thread, otherwise the UI will block during the download's progress.
Another example problem is to write a threaded ray tracer (here's an example tutorial written in C++).
If you want something simpler, write a Swing clock. Use a loop within a separate thread to update the UI at a periodic interval, but do not use the loop to manage what time it is. Again, don't try to keep time in the loop, just let the OS keep the time, and use the loop to schedule when the UI gets updated with the current OS time.
You're never calling getElapsedTime() that updates elapsed field.
You are creating a new Timer when ever you click the button. Make timer a class variable of your MyAction
The code below should be sufficient to get elapsed time.
class MyAction implements ActionListener {
final Timer timer = new Timer();
public void actionPerformed(ActionEvent e) {
String text = (String) e.getActionCommand();
if (text.equals("Start")) {
button.setText("Stop");
timer.startTime();
} else {
timer.stopTime();
System.out.println(timer.elapsed);
button.setText("Start");
}
}
}
Simply do this...
- Call System.currentTimeMillis() at the Starting of threads.
- Then again call System.currentTimeMillis() at the end of threads.
- Subtract the end with starting value to get the Elapsed time...
/////////////////EDITED///////////////////////
Make sure that the method trying to manipulate(ie. read and write) the variable holding the System.currentTimeMillis() must be synchronized, with synchronized keyword, so that Race Condition doesn't occur according to Brian's Law...
If you are writing a variable that might next be read by another thread, or reading a variable that might have last been written by another thread, you must use synchronization, and further, both the reader and the writer must synchronize using the same monitor lock.
I have a specific function that I want to be executed after 5 seconds.
How can I do that in Java?
I found javax.swing.timer, but I can't really understand how to use it. It looks like I'm looking for something way simpler then this class provides.
Please add a simple usage example.
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
5000
);
EDIT:
javadoc says:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.
Something like this:
// When your program starts up
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// then, when you want to schedule a task
Runnable task = ....
executor.schedule(task, 5, TimeUnit.SECONDS);
// and finally, when your program wants to exit
executor.shutdown();
There are various other factory methods on Executor which you can use instead, if you want more threads in the pool.
And remember, it's important to shutdown the executor when you've finished. The shutdown() method will cleanly shut down the thread pool when the last task has completed, and will block until this happens. shutdownNow() will terminate the thread pool immediately.
Example of using javax.swing.Timer
Timer timer = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Code to be executed
}
});
timer.setRepeats(false); // Only execute once
timer.start(); // Go go go!
This code will only be executed once, and the execution happens in 3000 ms (3 seconds).
As camickr mentions, you should lookup "How to Use Swing Timers" for a short introduction.
As a variation of #tangens answer: if you can't wait for the garbage collector to clean up your thread, cancel the timer at the end of your run method.
Timer t = new java.util.Timer();
t.schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
// close the thread
t.cancel();
}
},
5000
);
My code is as follows:
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here, and if you have to refresh UI put this code:
runOnUiThread(new Runnable() {
public void run() {
//your code
}
});
}
},
5000
);
Your original question mentions the "Swing Timer". If in fact your question is related to SWing, then you should be using the Swing Timer and NOT the util.Timer.
Read the section from the Swing tutorial on "How to Use Timers" for more information.
you could use the Thread.Sleep() function
Thread.sleep(4000);
myfunction();
Your function will execute after 4 seconds. However this might pause the entire program...
ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.
Timer also has this ability but opens several thread even if used only once.
Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):
public class JavaUtil {
public static void postDelayed(final Runnable runnable, final long delayMillis) {
final long requested = System.currentTimeMillis();
new Thread(new Runnable() {
#Override
public void run() {
// The while is just to ignore interruption.
while (true) {
try {
long leftToSleep = requested + delayMillis - System.currentTimeMillis();
if (leftToSleep > 0) {
Thread.sleep(leftToSleep);
}
break;
} catch (InterruptedException ignored) {
}
}
runnable.run();
}
}).start();
}
}
Test:
#Test
public void testRunsOnlyOnce() throws InterruptedException {
long delay = 100;
int num = 0;
final AtomicInteger numAtomic = new AtomicInteger(num);
JavaUtil.postDelayed(new Runnable() {
#Override
public void run() {
numAtomic.incrementAndGet();
}
}, delay);
Assert.assertEquals(num, numAtomic.get());
Thread.sleep(delay + 10);
Assert.assertEquals(num + 1, numAtomic.get());
Thread.sleep(delay * 2);
Assert.assertEquals(num + 1, numAtomic.get());
}
All other unswers require to run your code inside a new thread.
In some simple use cases you may just want to wait a bit and continue execution within the same thread/flow.
Code below demonstrates that technique. Keep in mind this is similar to what java.util.Timer does under the hood but more lightweight.
import java.util.concurrent.TimeUnit;
public class DelaySample {
public static void main(String[] args) {
DelayUtil d = new DelayUtil();
System.out.println("started:"+ new Date());
d.delay(500);
System.out.println("half second after:"+ new Date());
d.delay(1, TimeUnit.MINUTES);
System.out.println("1 minute after:"+ new Date());
}
}
DelayUtil Implementation
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class DelayUtil {
/**
* Delays the current thread execution.
* The thread loses ownership of any monitors.
* Quits immediately if the thread is interrupted
*
* #param duration the time duration in milliseconds
*/
public void delay(final long durationInMillis) {
delay(durationInMillis, TimeUnit.MILLISECONDS);
}
/**
* #param duration the time duration in the given {#code sourceUnit}
* #param unit
*/
public void delay(final long duration, final TimeUnit unit) {
long currentTime = System.currentTimeMillis();
long deadline = currentTime+unit.toMillis(duration);
ReentrantLock lock = new ReentrantLock();
Condition waitCondition = lock.newCondition();
while ((deadline-currentTime)>0) {
try {
lock.lockInterruptibly();
waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
currentTime = System.currentTimeMillis();
}
}
}
public static Timer t;
public synchronized void startPollingTimer() {
if (t == null) {
TimerTask task = new TimerTask() {
#Override
public void run() {
//Do your work
}
};
t = new Timer();
t.scheduleAtFixedRate(task, 0, 1000);
}
}
I think in this case :
import javax.swing.*;
import java.awt.event.ActionListener;
is the best. When the Question is prevent Ui stack or a progress not visible before a heavy work or network call. We can use the following methods (from my experience) :
Run a method after one Second :
public static void startMethodAfterOneSeconds(Runnable runnable) {
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(false); // Only execute once
timer.start();
}
Run a method after n second once, Non repeating :
public static void startMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
Timer timer = new Timer(milliSeconds, new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(false); // Only execute once
timer.start();
}
Run a method after n seconds, and repeat :
public static void repeatMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
Timer timer = new Timer(milliSeconds, new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(true); // Only execute once
timer.start();
}
And the Usage :
startMethodAfterNMilliseconds(new Runnable() {
#Override
public void run() {
// myMethod(); // Your method goes here.
}
}, 1000);
Perhaps the most transparent way is to use the postDelayed function of the Handler class the following way:
new Handler().postDelayed(this::function, 1000);
or you can implement the function inside, for example:
new Handler().postDelayed(() -> System.out.println("A second later"), 1000);
Where the first argument is the function, the second argument is the delay time in milliseconds.
In the first example, the name of the called function is "function".