Solved

Timer, TimerTask

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

ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Checkbox and ListView in Android Layout 4 65
recursion example 16 126
type mismatch (Object[] to double[] 4 24
throw exception 21 44
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
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…

770 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