Program not terminates after java.util.Timer usage - java

I have simple Timer console application. Why this application not stops after run procedure was executed and still waiting for something?
package timer_old;
import java.util.Timer;
import java.util.TimerTask;
public final class FetchMail extends TimerTask {
public static void main (String[] args)
{
System.out.println("starting");
TimerTask fetchMail = new FetchMail();
Timer timer = new Timer();
timer.schedule(fetchMail, 500);
//timer.cancel();
System.out.println("exiting");
}
public void run()
{
System.out.println("Fetching mail...");
}
}
Output:
starting
exiting
Fetching mail...

From the docs:
By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the timer's cancel method.

you need to call timer.cancel() when you want the timer to terminate as soon as the run is executed.
public final class FetchMail extends TimerTask {
static Timer timer=null;
public static void main (String[] args)
{
System.out.println("starting");
TimerTask fetchMail = new FetchMail();
timer= new Timer();
timer.schedule(fetchMail, 3000);
//timer.cancel();
System.out.println("exiting");
}
public void run()
{
System.out.println("Fetching mail...");
timer.cancel();
}
}

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.

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.

How to cancel timerTask for AsyncTask in android

Hi I am working on TCP socket.
I can read data for every 1 sec. to achieve it I used TimerTask as shown in below code.
Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
finalizer = new Runnable() {
public void run() {
try {
if (navBool) {
runOnUiThread(new Runnable() {
public void run() {
new RetriveStock().execute(); // AsyncTask.
}
});
}
} catch (Exception e) {
}
}
};
handler.post(finalizer);
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
For canceling this timer I used code as
timer.cancel();
timer = null;
handler.removeCallbacks(finalizer);
But it is not cancelling the timer. I do not know why.
Instead of calling timer.cancel(), you should be canceling the task that is assigned to that timer (doAsynchronousTask in your case). Since multiple TimerTasks can be assigned to one timer, calling timer.cancel() will not interfere with a currently running task.
From the Timer JavaDoc:
public void cancel()
Terminates this timer, discarding any currently scheduled tasks. Does
not interfere with a currently executing task (if it exists). Once a
timer has been terminated, its execution thread terminates gracefully,
and no more tasks may be scheduled on it.

Swing timer not Starting

I am trying to print a statement repeatedly using Swing Timer but the statement doesn't gets printed !
What's the mistake I am making ?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class SwingTimer implements ActionListener {
Timer timer;
public static void main(String[] args) {
SwingTimer obj = new SwingTimer();
obj.create();
}
public void create() {
timer = new Timer(1000, this);
timer.setInitialDelay(0);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello using Timer");
}
}
The javax.swing.Timer probably starts as a daemon thread: it doesn't keep the jvm alive, your main ends, the jvm exits. It post the timer events to the GUI event queue which starts when the first dialog or frame is made visible.
You have to create a JFrame, and make it visible or use the java.util.Timer if you don't need windowing system at all.
The following code shows how to use java.util.Timer:
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemo extends TimerTask {
private long time = System.currentTimeMillis();
#Override public void run() {
long elapsed = System.currentTimeMillis() - time;
System.err.println( elapsed );
time = System.currentTimeMillis();
}
public static void main( String[] args ) throws Exception {
Timer t = new Timer( "My 100 ms Timer", true );
t.schedule( new TimerDemo(), 0, 100 );
Thread.sleep( 1000 ); // wait 1 seconde before terminating
}
}
javax.swing.Timer should only be used when using Swing applications. Currently your main Thread is exiting as the Timer uses a daemon Thread. As a workaround you could do:
public static void main(String[] args) {
SwingTimer obj = new SwingTimer();
obj.create();
JOptionPane.showMessageDialog(null, "Timer Running - Click OK to end");
}
An alternative for non-UI applications is to use ScheduledExecutorService

Categories

Resources