summaryrefslogtreecommitdiffstats
path: root/mobile/android/services/src/main/java/org/mozilla/gecko/sync/PrefsBackoffHandler.java
blob: 63f6446da1230c2529fb7642079d8626bc1b59f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.sync;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class PrefsBackoffHandler implements BackoffHandler {
  public static final String PREF_EARLIEST_NEXT = "earliestnext";

  private final SharedPreferences prefs;
  private final String prefEarliest;

  public PrefsBackoffHandler(final SharedPreferences prefs, final String prefSuffix) {
    if (prefs == null) {
      throw new IllegalArgumentException("prefs must not be null.");
    }
    this.prefs = prefs;
    this.prefEarliest = PREF_EARLIEST_NEXT + "." + prefSuffix;
  }

  @Override
  public synchronized long getEarliestNextRequest() {
    return prefs.getLong(prefEarliest, 0);
  }

  @Override
  public synchronized void setEarliestNextRequest(final long next) {
    final Editor edit = prefs.edit();
    edit.putLong(prefEarliest, next);
    edit.commit();
  }

  @Override
  public synchronized void extendEarliestNextRequest(final long next) {
    if (prefs.getLong(prefEarliest, 0) >= next) {
      return;
    }
    final Editor edit = prefs.edit();
    edit.putLong(prefEarliest, next);
    edit.commit();
  }

  /**
   * Return the number of milliseconds until we're allowed to touch the server again,
   * or 0 if now is fine.
   */
  @Override
  public long delayMilliseconds() {
    long earliestNextRequest = getEarliestNextRequest();
    if (earliestNextRequest <= 0) {
      return 0;
    }
    long now = System.currentTimeMillis();
    return Math.max(0, earliestNextRequest - now);
  }
}