WorkManager中OneTimeWorkRequest的重试策略与最大重试次数咨询
WorkManager Retry Strategy When Worker Returns RETRY
Great question! Let me walk you through exactly how WorkManager handles retries when your SyncWorker keeps returning Result.RETRY:
Default Retry Behavior
- Backoff Policy: By default, WorkManager uses an exponential backoff strategy. That means the first retry will happen after 10 seconds, then 20 seconds, 40 seconds, 80 seconds, and so on. The delay doubles each time until it hits the default maximum delay of 5 minutes—after that, all subsequent retries will stick to the 5-minute interval.
- No Built-in Max Retry Limit: WorkManager doesn’t have a default cap on how many times it will retry your task. It’ll keep retrying indefinitely unless one of these scenarios occurs:
- Your worker returns
Result.SUCCESSorResult.FAILURE - You explicitly cancel the task (e.g., via
WorkManager.cancelWorkById()orcancelAllWorkByTag()) - The app is uninstalled, or WorkManager’s app data is cleared
- The device is factory reset
- Your worker returns
Customizing the Retry Strategy
If the default behavior doesn’t fit your needs, you can tweak the backoff rules when building your OneTimeWorkRequest:
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(SyncWorker.class) .setConstraints(constraints) .addTag(SyncWorker.TAG) // Switch to linear backoff with a 30-second initial delay .setBackoffCriteria(BackoffPolicy.LINEAR, 30, TimeUnit.SECONDS) .build();
BackoffPolicy.LINEAR: The delay increases by a fixed amount each time (e.g., 30s, 60s, 90s) instead of doubling.- You can adjust the initial delay and time unit to match your use case.
Adding a Custom Max Retry Limit
Since WorkManager doesn’t include a built-in max retry count, you’ll need to implement this logic yourself in your worker. Here’s a practical example:
public class SyncWorker extends Worker { public static final String TAG = "SyncWorker"; private static final String KEY_RETRY_COUNT = "retry_count"; private static final int MAX_RETRIES = 5; // Set your desired max retries here public SyncWorker(@NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @NonNull @Override public Result doWork() { // Get current retry count (default to 0 if not set) int retryCount = getInputData().getInt(KEY_RETRY_COUNT, 0); retryCount++; // Your sync task logic goes here... // Stop retrying if we've hit the max limit if (retryCount >= MAX_RETRIES) { return Result.failure(); } else { // Pass the updated retry count to the next attempt Data outputData = new Data.Builder() .putInt(KEY_RETRY_COUNT, retryCount) .build(); return Result.retry(outputData); } } }
内容的提问来源于stack exchange,提问作者Cheok Yan Cheng
相关产品推荐
相关产品推荐

