Skip to content

Instantly share code, notes, and snippets.

@sfeatherstone
Last active April 30, 2020 14:55
Show Gist options
  • Save sfeatherstone/8c21ac2fe8af4776f783a0c1364139b5 to your computer and use it in GitHub Desktop.
Save sfeatherstone/8c21ac2fe8af4776f783a0c1364139b5 to your computer and use it in GitHub Desktop.
WM REST: worker constructor and worker
class PostToServerWorker(appContext: Context, workerParams: WorkerParameters)
: CoroutineWorker(appContext, workerParams) {
private val random by lazy { Random(Date().time)}
override suspend fun doWork(): Result {
// Read input data
val jobDuration = inputData.getInt(JOB_TIME, 100)
val jobSuccessRate = inputData.getInt(JOB_SUCCESS_CHANCE, 0)
val maxAttempts = inputData.getInt(ATTEMPT_RETRIES, 5)
log("Starting job", maxAttempts)
//Fake some work with progress
setProgress(workDataOf(Progress to 0))
for (i in 1..10) {
// Simulate work
delay((jobDuration / 10).toLong())
setProgress(workDataOf(Progress to i * 10))
}
// Add a random fail
if (random.nextInt(100) > jobSuccessRate) {
// Get number of attempts made against max attempts we have set
if (runAttemptCount <= maxAttempts) {
// Try again
log("Retrying job", maxAttempts)
return Result.retry()
}
log("Failing job", maxAttempts)
return Result.failure()
}
// Return the output
log("Finishing successful job", maxAttempts)
return Result.success()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment