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 (ie 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);
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
I am currently developing similar things in android. See if this helps you:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(getReloadTask(position), 0, 20, TimeUnit.SECONDS);
链接地址: http://www.djcxy.com/p/38954.html
下一篇: ScheduledThreadPoolExecutor用于周期性任务(使用Retrofit),只发射一次,不再发生