views:

527

answers:

4

Hello,

I want to auto-schedule a thread with a particular time interval. I also need to execute this in the background continously without hangs to the device.

I have tried this with Application Manager Class but it's for application scheduling and I need to schedule thread within the application.

A: 

As long as the application is running - just create the thread and after each bit of work call Thread.sleep for as long as you need it to stay dormant.

If you need it to wake up at a particular time, rather than just sleep for a particular time, then you can do something like the following:

Date wakeUpAt = ...; // Get this however
Date now = new Date();
long millisToSleepFor = wakeUpAt.getTime() - now.getTime();
Thread.sleep(millisToSleepFor);
Andrzej Doyle
Thanks but in sleep it hangs for given time (long millisToSleepFor) time.
Rishabh
Are you saying that while the Thread is sleeping, the device doesn't schedule any other threads? The whole point of sleep() is that the thread isn't scheduled on the CPU for that amount of time...
Andrzej Doyle
A: 

use UiApplication.getUiApplication().invokeLater() it accepts a delay and repeat parameters and will perform exactly what you need.

Reflog
Right, but Is there way that thread starts to excute after exiting application at a given delay for example delay of 1 day.
Rishabh
+1  A: 

Assuming you want it to run a thread on device startup: Create a second project and list it as an alternate entry point. In your UiApplication or Application main(), check the argument passed to the project. Do your periodic stuff there via Thread.sleep and don't call enterEventDispatcher.

search for "autostart": http://docs.blackberry.com/en/developers/deliverables/1076/development.pdf

Or if you want to do something once a user "starts" it, then look into creating a new thread to do your timing stuff. Override your screen's onClose() and use Application.getActivation().deactivate() to throw the screen into the background.

Or there's a other ways to do something like this like invokeLater, etc. Maybe eventlisteners may do what you need, but you didn't give a lot of details.

nope
A: 

I would use TimerTask:

public class MyScreen extends MainScreen {
    private Timer mTimer;
    public MyScreen() {        
        mTimer = new Timer();
        //start after 1 second, repeat every 5 second
        mTimer.schedule(mTimerTask, 0, 500);
    }

    TimerTask mTimerTask = new TimerTask() {
        public void run() {
            // some processing here
        }
    };
}

see BlackBerry API Hidden Gems (Part Two)

Max Gontar