mobile/android/base/sync/PrefsBackoffHandler.java

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/mobile/android/base/sync/PrefsBackoffHandler.java	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,59 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +package org.mozilla.gecko.sync;
     1.9 +
    1.10 +import android.content.SharedPreferences;
    1.11 +import android.content.SharedPreferences.Editor;
    1.12 +
    1.13 +public class PrefsBackoffHandler implements BackoffHandler {
    1.14 +  public static final String PREF_EARLIEST_NEXT = "earliestnext";
    1.15 +
    1.16 +  private final SharedPreferences prefs;
    1.17 +  private final String prefEarliest;
    1.18 +
    1.19 +  public PrefsBackoffHandler(final SharedPreferences prefs, final String prefSuffix) {
    1.20 +    if (prefs == null) {
    1.21 +      throw new IllegalArgumentException("prefs must not be null.");
    1.22 +    }
    1.23 +    this.prefs = prefs;
    1.24 +    this.prefEarliest = PREF_EARLIEST_NEXT + "." + prefSuffix;
    1.25 +  }
    1.26 +
    1.27 +  @Override
    1.28 +  public synchronized long getEarliestNextRequest() {
    1.29 +    return prefs.getLong(prefEarliest, 0);
    1.30 +  }
    1.31 +
    1.32 +  @Override
    1.33 +  public synchronized void setEarliestNextRequest(final long next) {
    1.34 +    final Editor edit = prefs.edit();
    1.35 +    edit.putLong(prefEarliest, next);
    1.36 +    edit.commit();
    1.37 +  }
    1.38 +
    1.39 +  @Override
    1.40 +  public synchronized void extendEarliestNextRequest(final long next) {
    1.41 +    if (prefs.getLong(prefEarliest, 0) >= next) {
    1.42 +      return;
    1.43 +    }
    1.44 +    final Editor edit = prefs.edit();
    1.45 +    edit.putLong(prefEarliest, next);
    1.46 +    edit.commit();
    1.47 +  }
    1.48 +
    1.49 +  /**
    1.50 +   * Return the number of milliseconds until we're allowed to touch the server again,
    1.51 +   * or 0 if now is fine.
    1.52 +   */
    1.53 +  @Override
    1.54 +  public long delayMilliseconds() {
    1.55 +    long earliestNextRequest = getEarliestNextRequest();
    1.56 +    if (earliestNextRequest <= 0) {
    1.57 +      return 0;
    1.58 +    }
    1.59 +    long now = System.currentTimeMillis();
    1.60 +    return Math.max(0, earliestNextRequest - now);
    1.61 +  }
    1.62 +}
    1.63 \ No newline at end of file

mercurial