Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScheduledThreadPoolExecutor for a periodic task (using Retrofit) just firing once and never again

I have the following code for polling the unread notification count every X seconds from a server

I start the this process via ScheduledThreadPoolExecutor in the App.onCreate() and

Log.d("XXX", "Requesting Notification count from server ...");

is called once (i can see in Logcat), but neither of the two Retrofit call back functions getting called (and in fact no Retrofit debug logs). Morever, the "Requesting Notification count from server...." is never printed again (i.e. the periodic task is not running)

I am using Retrofit for other webservice calls as well (upon user input) and they are working fine (I can see the incoming and outgoing requests/responses in the logcat)

public class App extends Application  {



    private ScheduledExecutorService scheduleTaskExecutor;
    ...


    @Override
    public void onCreate() {
        super.onCreate();

        //region Set up the periodic notification count listener task


        scheduleTaskExecutor= Executors.newScheduledThreadPool(2);
        scheduleTaskExecutor.scheduleAtFixedRate(new PeriodicNotifCountFetchTask(), 0, 5, TimeUnit.SECONDS);

        //endregion
    }


    class PeriodicNotifCountFetchTask implements Runnable {

        @Override
        public void run() {
            Log.d("XXX", "Requesting Notification count from server ...");
            EMRestClient.getmEMRestService().getNotificationCount(new Callback<NotificationCount>() {
                @Override
                public void success(NotificationCount response, Response unused) {

                    int unreadNotifCount = response.getCount();

                    Log.d("XXX", "Successfully fetched notification count, unread = " + response.getCount());
                    if (unreadNotifCount>0){
                        // call listener to repaint menu
                        for (NewNotificationListener x :notifListeners){
                            x.onNewNotificationReceived(response.getCount());    
                        }
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    Log.d("XXX", "Failed to fetch notification count from server");
                }
            });

        }
    }


}

The retrofit part of the code is here:

    @POST("/notification/notification_count/")
    void getNotificationCount(Callback<NotificationCount> callback);
like image 803
dowjones123 Avatar asked Sep 29 '22 01:09

dowjones123


1 Answers

There may be some exception will be occuring because of which subsequent calls will be suppressed. ScheduledThreadPoolExecutor only "ticking" once

So try to put your code inside runnable of runOnUiThread like Scheduling recurring task in Android

like image 91
Anand Gupta Avatar answered Oct 06 '22 19:10

Anand Gupta