Solved

Timer, TimerTask

Posted on 2014-04-27
3
339 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

728 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