Solved

Timer, TimerTask

Posted on 2014-04-27
3
337 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 27

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

828 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