• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 343
  • Last Modified:

Timer, TimerTask

So I am putting together some code and need to use a Timer, I think. I came across several examples of how to implement the Timer (see code). I noticed when the Timer is called it runs and does its thing just fine, however I noticed:

1. The calling thread continues to run the code within its scope
2. After the TimerTask has completed it appears not to return back to the thread that called it.

For example in this code the line after calling the Timer executes. In other words System.out.println("Done") runs while the TimerTask is doing its thing. Also after the TimerTask is finished with the This.cancel nothing else happens. The app doesn't close or execute any more code.

How do I prevent the code from running in the calling thread after calling the Timer?
And how to I get the TimerTask to return back to the calling thread?
Or is there some other method I could implement that would do these things?

import java.util.Timer;
import java.util.TimerTask;
 

public class TimerSample {
   public String tst = "Testing ";
    public static void main(String[] args) {
        //1- Taking an instance of Timer class.
        Timer timer = new Timer("Printer");
   
        //2- Taking an instance of class contains your repeated method.
        MyTask t = new MyTask();
 
 
        //TimerTask is a class implements Runnable interface so
        //You have to override run method with your certain code black
 
        //Second Parameter is the specified the Starting Time for your timer in
        //MilliSeconds or Date
 
        //Third Parameter is the specified the Period between consecutive
        //calling for the method.
 
        timer.schedule(t, 0, 2000);
 
      System.out.println("DOne");
    }
}
 
class MyTask extends TimerTask {
    //times member represent calling times.
    private int times = 0;
   TimerSample testit = new TimerSample();
 
    public void run() {
        times++;
        if (times <= 5) {
            System.out.println(testit.tst + times);
        } else {
            System.out.println("Timer stops now...");
 
            //Stop Timer.
            this.cancel();
            return;
        }
    }
}

Open in new window

0
CrazyOne
Asked:
CrazyOne
1 Solution
 
dpearsonCommented:
The method that starts the timer runs in its own thread, so the whole idea is that both keep running at the same time (which is why you are using a new thread).  That's why "Done" is printed immediately - the main thread doesn't normally want to block and wait for the result from the timer.

Also "this.cancel()" cancels the TimerTask, not the Timer.  So it stops it from calling to MyTask but the timer itself is still there (the separate thread) and that stops the application from finishing.

Try something like this instead.  It has the main thread explicitly waiting for the Timer to finish by checking on the state of the "times" variable and waiting for it to reach 5.

public class Application {
	public String tst = "Testing ";
	public static void main(String[] args) {
		//1- Taking an instance of Timer class.
		Timer timer = new Timer("Printer");

		//2- Taking an instance of class contains your repeated method.
		MyTask t = new MyTask();


		//TimerTask is a class implements Runnable interface so
		//You have to override run method with your certain code black

		//Second Parameter is the specified the Starting Time for your timer in
		//MilliSeconds or Date

		//Third Parameter is the specified the Period between consecutive
		//calling for the method.

		timer.schedule(t, 0, 2000);

		// Wait for the task to finish
		do {
			try { Thread.sleep(100); } catch (Exception ex) { }
		} while (t.getTimes() <= 5) ;

		System.out.println("Done");

		// Now cancel the Timer - so the application can exit cleanly
		timer.cancel();
	}
}

class MyTask extends TimerTask {
	//times member represent calling times.
	private int times = 0;
	public MyTask() {
	}

	public int getTimes() { return times ; }

	public void run() {
		times++;
		if (times <= 5) {
			System.out.println("Counter is " + times) ;
		} else {
			System.out.println("Timer stops now...");

			//Stop Timer task - not timer
			this.cancel();
			return;
		}
	}
} ;

Open in new window


Hope that helps,

Doug
0
 
CrazyOneAuthor Commented:
I kinda visioned it to be that way, oh well.
0
 
krakatoaCommented:
Hi CrazyOne -

@Doug :

I can open a new Q on this if you like, but I was wondering - I have a class that extends TimerTask, with a Timer as one of its fields. I was wondering then according to your answer Doug, whether the way I've done it is correct, since the Task ends by this.cancel(). I was assuming that doing it this way would kill 2 birds with one stone. The extended Task class thread doesn't *appear* to be left running. - ? -
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now