From: Marius Gavrilescu Date: Sat, 23 Mar 2013 11:54:39 +0000 (+0200) Subject: Make ExecutableRunnable usable X-Git-Tag: 0.000_001~46 X-Git-Url: http://git.ieval.ro/?a=commitdiff_plain;h=e154bdfd76071b99635317ef8c7ab11918b88794;p=fonbot.git Make ExecutableRunnable usable First of all, the retry mechanism did not work at all until now (if a task was retried ExecutableRunnable would stack overflow). Secondly, ExecutableRunnable now prevents retryTasks from being called too frequently. If it detects that retryTasks was called twice in 30 seconds, it reschedules the call 30 seconds later. --- diff --git a/src/ro/ieval/fonbot/ExecutableRunnable.java b/src/ro/ieval/fonbot/ExecutableRunnable.java index 642661b..13addac 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,17 +41,35 @@ 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 executor = Executors.newSingleThreadScheduledExecutor(); /** Queue containing ExecutableRunnables that should be retried */ private static final Queue retryPendingTasks = new LinkedList(); + /** Minimum interval between task retries, in milliseconds */ + private static final long retryInterval = 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 #executor} */ + private static volatile boolean retryIsScheduled = false; /** Run all tasks that should be retried */ public static final void retryTasks(){ + if(!retryIsScheduled && lastRetry+retryInterval>SystemClock.elapsedRealtime()){ + retryIsScheduled = true; + executor.schedule(new Runnable() { + @Override + public void run() { + retryTasks(); + retryIsScheduled = false; + } + }, retryInterval, TimeUnit.MILLISECONDS); + return; + } synchronized(retryPendingTasks){ for(ExecutableRunnable task : retryPendingTasks) - task.execute(); + executor.execute(task); retryPendingTasks.clear(); } + lastRetry=SystemClock.elapsedRealtime(); } /** Execute this ExecutableRunnable */