Solved

Timer, TimerTask

Posted on 2014-04-27
3
333 Views
Last Modified: 2014-04-29
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
Comment
Question by:CrazyOne
3 Comments
 
LVL 26

Accepted Solution

by:
dpearson earned 500 total points
ID: 40025986
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
 
LVL 44

Author Closing Comment

by:CrazyOne
ID: 40028040
I kinda visioned it to be that way, oh well.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40029176
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now