简体   繁体   中英

Android where to create ScheduledThreadPool and what happens if not shutdown?

I am creating a ScheduledThreadPool to run some method calls periodically. For an example I want to save everything to the DB every 10 seconds... So I got:

public class Scheduler{
    ScheduledExecutorService scheduledExecutorService =
        Executors.newScheduledThreadPool(5);

public Scheduler(){
    foo = Foo.getInstance();

    saveValues();
}

private void saveValues(){
    ScheduledFuture saveValues = scheduledExecutorService.scheduleAtFixedRate(
            new Runnable(){
                public void run() {
                    Log.e(TAG, "in save values");

                    foo.save();
                }
            }, 2000, 2000, TimeUnit.MILLISECONDS);
}
}

but the problem is it runs once and never again. I read in one tutorial that it is important to shut down the Executer cause it might run on forever otherwise so I expected I did not need to take care of it's lifecycle except for creating it and shutting it down at one point.

Foo is an Api which is a singleton. It gets called by the activity and calls Scheduler . I was also wondering if it should extend Application, but did not find it necessary yet.

Where in my app do I need to call it, is it ok in the Scheduler class or not? Does Scheduler need to be a Runnable? And where exactly do I shut down the Executer?

Thanks in advance

ps: if you think that an Executer is not the right way to do it, let me know. I looked through many threads and pages and did not find a perfect answer so the Executer seemed alright.

Should it be bound to just one Activity? of you need the functionality across your application even if the activity is destroyed?

I made such functionality extending Service. Here is the code:

public class MyService extends Service {

    static final public String SERVICE_RESULT = "com.my.app.MyService.SMS_UPDATED";
    static final public String SERVICE_MESSAGE = "SMS updated";

    int SECONDS = 10;

    LocalBroadcastManager broadcaster;

    ScheduledExecutorService scheduledExecutorService =
            Executors.newScheduledThreadPool(5);


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        ScheduledFuture scheduledFuture =
                scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {

                      // do some processing... and then

                      sendResult(SERVICE_MESSAGE);

                    }
                }, SECONDS, SECONDS, TimeUnit.SECONDS);

        return Service.START_STICKY;

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        broadcaster = LocalBroadcastManager.getInstance(this);

       // if you need any initialization...
    }


    public void sendResult(String message) {
        Intent intent = new Intent(SERVICE_RESULT);
        if (message != null)
            intent.putExtra(SERVICE_RESULT, message);
        broadcaster.sendBroadcast(intent);
    }
}

So, I use an intent to communicate the result of the processing back to my app. By using the scheduleAtFixedRate I am able to run the task every 10 seconds, you should modify it to your needs. Then, notice the Service.START_STICKY; it defines if the service should be restarted or not.

The code you posted seems to be correct, but, if it's within an activiy and you need it in others.. maybe it's being destroyed.

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