X-Git-Url: http://git.ieval.ro/?a=blobdiff_plain;f=src%2Fro%2Fieval%2Ffonbot%2FExecutableRunnable.java;h=4011338c4d2e9de175c50b3e1b3590f1e37a9db3;hb=62f5262d8bfa537f2b173c0309f1128054cf0916;hp=642661b4ccd4ac40a20e83dfb1964fdf425257be;hpb=bf70dcc30a9bd5cbcd71aa8481f7171331f9f1b6;p=fonbot.git diff --git a/src/ro/ieval/fonbot/ExecutableRunnable.java b/src/ro/ieval/fonbot/ExecutableRunnable.java index 642661b..4011338 100644 --- a/src/ro/ieval/fonbot/ExecutableRunnable.java +++ b/src/ro/ieval/fonbot/ExecutableRunnable.java @@ -2,8 +2,11 @@ package ro.ieval.fonbot; import java.util.LinkedList; import java.util.Queue; -import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import android.os.SystemClock; /* * Copyright © 2013 Marius Gavrilescu @@ -38,29 +41,47 @@ import java.util.concurrent.Executors; */ abstract class ExecutableRunnable implements Runnable { /** Executor used to execute instances of this class */ - private static final Executor executor = Executors.newSingleThreadExecutor(); + private static final ScheduledExecutorService EXECUTORS = Executors.newSingleThreadScheduledExecutor(); /** Queue containing ExecutableRunnables that should be retried */ - private static final Queue retryPendingTasks = new LinkedList(); + private static final Queue RETRY_PENDING_TASKS = new LinkedList(); + /** Minimum interval between task retries, in milliseconds */ + private static final long RETRY_INTERVAL = 30000; + /** {@link SystemClock#elapsedRealtime()} time of last successful call to {@link #retryTasks()} */ + private static long lastRetry = 0; + /** True if a retryTasks run is already scheduled on {@link #EXECUTORS} */ + private static volatile boolean retryIsScheduled = false; /** Run all tasks that should be retried */ public static final void retryTasks(){ - synchronized(retryPendingTasks){ - for(ExecutableRunnable task : retryPendingTasks) - task.execute(); - retryPendingTasks.clear(); + if(!retryIsScheduled && lastRetry+RETRY_INTERVAL>SystemClock.elapsedRealtime()){ + retryIsScheduled = true; + EXECUTORS.schedule(new Runnable() { + @Override + public void run() { + retryTasks(); + retryIsScheduled = false; + } + }, RETRY_INTERVAL, TimeUnit.MILLISECONDS); + return; + } + synchronized(RETRY_PENDING_TASKS){ + for(ExecutableRunnable task : RETRY_PENDING_TASKS) + EXECUTORS.execute(task); + RETRY_PENDING_TASKS.clear(); } + lastRetry=SystemClock.elapsedRealtime(); } /** Execute this ExecutableRunnable */ public final void execute(){ retryTasks(); - executor.execute(this); + EXECUTORS.execute(this); } /** Mark this ExecutableRunnable as needing to be retried later */ protected final void retry(){ - synchronized(retryPendingTasks){ - retryPendingTasks.add(this); + synchronized(RETRY_PENDING_TASKS){ + RETRY_PENDING_TASKS.add(this); } } }