ScheduledThreadPoolExecutor用于周期性任务(使用Retrofit),只发射一次,不再发生

我有以下代码用于每隔X秒从服务器轮询未读通知计数

我通过App.onCreate()中的ScheduledThreadPoolExecutor开始这个过程

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

被调用一次(我可以在Logcat中看到),但是两个Retrofit回调函数都没有调用(实际上没有Retrofit调试日志)。 此外,“从服务器请求通知计数...”不会再次打印(即周期性任务未运行)

我也使用Retrofit进行其他web服务调用(在用户输入时),它们工作正常(我可以在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");
                }
            });

        }
    }


}

代码的改进部分在这里:

    @POST("/notification/notification_count/")
    void getNotificationCount(Callback<NotificationCount> callback);

可能会出现一些异常,因为后续调用将被抑制。 ScheduledThreadPoolExecutor只能“滴答”一次

因此,请尝试将代码放入RunOnUiThread的runnable中,例如Android中的计划重复任务


我目前在android中开发类似的东西。 看看这是否有助于你:

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(getReloadTask(position), 0, 20, TimeUnit.SECONDS);
链接地址: http://www.djcxy.com/p/38953.html

上一篇: ScheduledThreadPoolExecutor for a periodic task (using Retrofit) just firing once and never again

下一篇: Running a service in separate thread and waking it every 10 minutes?