简体   繁体   中英

How can I schedule a particular thread in Blackberry

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.

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, 5000);
    }

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

see BlackBerry API Hidden Gems (Part Two)

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

EDIT

I know this post is old but this is by far the best option to schedule repeating events and I would like to add that to stop the scheduled event the following is required:

//Start repeating "runnable" thread every 10 seconds and save the event ID
int eventId = UiApplication.getUiApplication().invokeLater(runnable, 10000, true);

//Cancel the repetition by the saved ID
UiApplication.getUiApplication().cancelInvokeLater(eventId);

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM