一个定期任务的 ScheduledThreadPoolExecutor(使用 Retrofit)只会触发一次,然后永远不会再次触发

5
我有以下代码用于从服务器每隔 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");
                }
            });

        }
    }


}

这里是 Retrofit 代码的部分:

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

你好 dowjones123,你有解决方案吗?如果有,请分享一下。 - abhishek kumar gupta
2个回答

3

1

我目前在开发类似的Android应用。看看这是否能帮助到你:

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(getReloadTask(position), 0, 20, TimeUnit.SECONDS);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接