Skip to content

Commit 65dbe1e

Browse files
author
Sebastian Roth
authored
Clarify how retries are handled (#274)
1 parent 9f5d2a8 commit 65dbe1e

File tree

4 files changed

+78
-20
lines changed

4 files changed

+78
-20
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,18 @@ void main() {
4141
4242
---
4343

44+
# Work Result
45+
46+
The `Workmanager().executeTask(...` block supports 3 possible outcomes:
47+
48+
1. `Future.value(true)`: The task is successful.
49+
2. `Future.value(false)`: The task did not complete successfully and needs to be retried.
50+
3. `Future.error(...)`: The task failed.
51+
52+
On Android, the `BackoffPolicy` will configure how `WorkManager` is going to retry the task.
53+
54+
Refer to the example app for a successful, retrying and a failed task.
55+
4456
# Customisation (Android only!)
4557
Not every `Android WorkManager` feature is ported.
4658

@@ -131,6 +143,7 @@ Add some input data for your task. Valid value types are: `int`, `bool`, `double
131143
},
132144
);
133145
```
146+
134147
## BackoffPolicy
135148
Indicates the waiting strategy upon task failure.
136149
The default is `BackoffPolicy.exponential`.

android/src/main/kotlin/be/tramckrijte/workmanager/BackgroundWorker.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package be.tramckrijte.workmanager
33
import android.content.Context
44
import android.os.Handler
55
import android.os.Looper
6+
import android.util.Log
67
import androidx.concurrent.futures.ResolvableFuture
78
import androidx.work.ListenableWorker
89
import androidx.work.WorkerParameters
@@ -30,6 +31,8 @@ class BackgroundWorker(
3031
private lateinit var backgroundChannel: MethodChannel
3132

3233
companion object {
34+
const val TAG = "BackgroundWorker"
35+
3336
const val PAYLOAD_KEY = "be.tramckrijte.workmanager.INPUT_DATA"
3437
const val DART_TASK_KEY = "be.tramckrijte.workmanager.DART_TASK"
3538
const val IS_IN_DEBUG_MODE_KEY = "be.tramckrijte.workmanager.IS_IN_DEBUG_MODE_KEY"
@@ -131,7 +134,8 @@ class BackgroundWorker(
131134
stopEngine(Result.failure())
132135
}
133136

134-
override fun error(p0: String?, p1: String?, p2: Any?) {
137+
override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) {
138+
Log.e(TAG, "errorCode: $errorCode, errorMessage: $errorMessage")
135139
stopEngine(Result.failure())
136140
}
137141

example/lib/main.dart

Lines changed: 57 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'dart:async';
22
import 'dart:io';
3+
import 'dart:math';
34

45
import 'package:flutter/material.dart';
56
import 'package:path_provider/path_provider.dart';
@@ -9,6 +10,8 @@ import 'package:workmanager/workmanager.dart';
910
void main() => runApp(MyApp());
1011

1112
const simpleTaskKey = "simpleTask";
13+
const rescheduledTaskKey = "rescheduledTask";
14+
const failedTaskKey = "failedTask";
1215
const simpleDelayedTask = "simpleDelayedTask";
1316
const simplePeriodicTask = "simplePeriodicTask";
1417
const simplePeriodic1HourTask = "simplePeriodic1HourTask";
@@ -22,6 +25,20 @@ void callbackDispatcher() {
2225
prefs.setBool("test", true);
2326
print("Bool from prefs: ${prefs.getBool("test")}");
2427
break;
28+
case rescheduledTaskKey:
29+
final key = inputData!['key']!;
30+
final prefs = await SharedPreferences.getInstance();
31+
if (prefs.containsKey('unique-$key')) {
32+
print('has been running before, task is successful');
33+
return true;
34+
} else {
35+
await prefs.setBool('unique-$key', true);
36+
print('reschedule task');
37+
return false;
38+
}
39+
case failedTaskKey:
40+
print('failed task');
41+
return Future.error('failed');
2542
case simpleDelayedTask:
2643
print("$simpleDelayedTask was executed");
2744
break;
@@ -34,7 +51,7 @@ void callbackDispatcher() {
3451
case Workmanager.iOSBackgroundTask:
3552
print("The iOS background fetch was triggered");
3653
Directory? tempDir = await getTemporaryDirectory();
37-
String? tempPath = tempDir?.path;
54+
String? tempPath = tempDir.path;
3855
print(
3956
"You can access other plugins in the background, for example Directory.getTemporaryDirectory(): $tempPath");
4057
break;
@@ -95,21 +112,45 @@ class _MyAppState extends State<MyApp> {
95112
//This task runs once.
96113
//Most likely this will trigger immediately
97114
PlatformEnabledButton(
98-
platform: _Platform.android,
99-
child: Text("Register OneOff Task"),
100-
onPressed: () {
101-
Workmanager().registerOneOffTask(
102-
"1",
103-
simpleTaskKey,
104-
inputData: <String, dynamic>{
105-
'int': 1,
106-
'bool': true,
107-
'double': 1.0,
108-
'string': 'string',
109-
'array': [1, 2, 3],
110-
},
111-
);
112-
}),
115+
platform: _Platform.android,
116+
child: Text("Register OneOff Task"),
117+
onPressed: () {
118+
Workmanager().registerOneOffTask(
119+
"1",
120+
simpleTaskKey,
121+
inputData: <String, dynamic>{
122+
'int': 1,
123+
'bool': true,
124+
'double': 1.0,
125+
'string': 'string',
126+
'array': [1, 2, 3],
127+
},
128+
);
129+
},
130+
),
131+
PlatformEnabledButton(
132+
platform: _Platform.android,
133+
child: Text("Register rescheduled Task"),
134+
onPressed: () {
135+
Workmanager().registerOneOffTask(
136+
"1-rescheduled",
137+
rescheduledTaskKey,
138+
inputData: <String, dynamic>{
139+
'key': Random().nextInt(64000),
140+
},
141+
);
142+
},
143+
),
144+
PlatformEnabledButton(
145+
platform: _Platform.android,
146+
child: Text("Register failed Task"),
147+
onPressed: () {
148+
Workmanager().registerOneOffTask(
149+
"1-failed",
150+
failedTaskKey,
151+
);
152+
},
153+
),
113154
//This task runs once
114155
//This wait at least 10 seconds before running
115156
PlatformEnabledButton(

lib/src/workmanager.dart

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ typedef BackgroundTaskHandler = Future<bool> Function(
2929
///
3030
/// ```
3131
/// void callbackDispatcher() {
32-
/// Workmanager.executeTask((taskName, inputData) {
32+
/// Workmanager().executeTask((taskName, inputData) {
3333
/// switch(taskName) {
3434
/// case "":
3535
/// print("Replace this print statement with your code that should be executed in the background here");
@@ -40,7 +40,7 @@ typedef BackgroundTaskHandler = Future<bool> Function(
4040
/// }
4141
///
4242
/// void main() {
43-
/// Workmanager.initialize(callbackDispatcher);
43+
/// Workmanager().initialize(callbackDispatcher);
4444
/// }
4545
/// ```
4646
///
@@ -66,7 +66,7 @@ class Workmanager {
6666
///
6767
/// ```
6868
/// void callbackDispatcher() {
69-
/// Workmanager.executeTask((taskName, inputData) {
69+
/// Workmanager().executeTask((taskName, inputData) {
7070
/// switch (taskName) {
7171
/// case Workmanager.iOSBackgroundTask:
7272
/// stderr.writeln("The iOS background fetch was triggered");

0 commit comments

Comments
 (0)