检查上一次任务执行并启动ScheduledExecutorService

时间:2019-07-25 15:13:39

标签: java android scheduled-tasks

我在应用程序内部实现了一个后台服务,该服务包含以下scheduleTaskExecutor:

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            fsize = FileManager.folderSize(folder);
            showS = FileManager.formatFileSize(fsize);
            Log.d("BackgroundService","Starting scheduleTaskExecutor");
            if(fsize>0){
                try {
                    FileManager.deleteFiles(folder);
                    Log.d("Deleting","Ok");
                }catch (Exception e){
                    Log.d("Deleting","errore"+e);
                }

                NotificationCompat.Builder builder = new NotificationCompat.Builder(BackgroundService.this, channelId)
                        .setContentTitle(BackgroundService.this.getResources().getString(R.string.delete_n_title))
                        .setContentText(BackgroundService.this.getResources().getString(R.string.delete_n_text, showS))
                        .setSmallIcon(R.drawable.ic_short_broom_b)
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT);
                Log.i("BackgroundService", "Notification called");
                NotificationManagerCompat notificationManager = NotificationManagerCompat.from(BackgroundService.this);
                notificationManager.notify(1, builder.build());
            }

        }
    }, 0, 3, TimeUnit.MINUTES);

如果后台服务被终止,则重新启动接收器将重新启动它。

问题是,如果后台服务在scheduleTaskExecutor固定速率(在我的情况下为3分钟)之前被杀死,那么scheduleTaskExecutor会认为这是第一次运行,并且无论如何都会运行代码而不会遵守我的参数(每3分钟运行一次)

如何检查距上一次scheduleTaskExecutor的运行是否有3分钟以上,然后执行run()方法是否为真?

0 个答案:

没有答案