TimerTask problems!

31Jul09

Having problems setting up a timed action in your Blackberry program when using Timer() and schedule. Let me take a few moments to break down how to setup a recurring task utilizing TimerTask.

A TimerTask is a set of actions that are called from a Timer that is running on a schedule.

Timer theTimer = new Timer();

TimerTask tt = new TimerTask() {

public void run ()

{

System.out.println(“1 Second”);

}

}

theTimer.schedule(tt,1000,1000);

I’ve created a Timer object and a TimerTask and set the TimerTask to a scchedule that begins 1000 milliseconds after the initial call and will repeat every 1000 milliseconds until it is cancelled.

The problem I had was I couldn’t figure out how to stop and start the schedule. You have three options.

  1. Cancel the Timer. Using theTimer.cancel() you will stop the schedule, stop the TimerTask and destroy the Timer. The problem is you can’t recreate it on the Blackberry. Every time you do you get an error message.
  2. Cancel the TimerTask. Using tt.cancel() you will stop the TimerTask and destoy the TimerTask. The problem is you can’t call on the TimerTask again since it no longer exisits, so you can’t start the TimerTask, then cancel the TimerTask, and then start another schedule that uses the TimerTask because it no longer exists.
  3. Cancel the TimerTask and recreate the TimerTask before setting up a new schedule. The Timer doesn’t need to be cancelled, just the task. If you cancel the task then it ceases to exist. So to start, stop, start, stop, etc. a task you must recreate the TimerTask. So you must ensure that somewhere between the TimerTask cancel – tt.cancel() – and the next scheudle call – theTimer.schedule(tt,1000,1000).

I wasn’t able to find a clear reason for the problems I was facing using TimerTask and thought I would write something up for future generations. You will be able to see this in action in the source code for Comedy Timing in the near future.

Advertisements


No Responses Yet to “TimerTask problems!”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: