-
Notifications
You must be signed in to change notification settings - Fork 395
Canceling Jobs
It is a common requirement that sometimes you notice a Job will not be needed anymore, like when a user leaves an activity or a user cancel an operation.
To achieve this, you can use job tags to identify your Jobs and later reference them to cancel using JobManager#cancelJobs or JobManager#cancelJobsInBackground.
Note that if a job is already running when cancel request arrives, JobManager will wait until Job#onRun method finishes (so no thread interrupts to stop the job). If you have a long running onRun
method, you can check Job#isCancelled and if it returns true, just throw an exception to immediately stop the Job.
Here is an example on how you could cancel all jobs created for an Activity when it becomes invisible. This sample uses onStart
& onStop
tuple, but you could as well use onCreate
and onDestroy
.
public class BaseActivity extends Activity {
...
private String sessionId;
private JobManager jobManager; //preferably injected
@Override
protected void onStart() {
super.onStart();
sessionId = UUID.randomUUID().toString();
}
@Override
protected void onStop() {
super.onStop();
jobManager.cancelJobsInBackground(null, TagConstraint.ANY, sessionId);
}
public void addActivityJob(Job job, Params params) {
params.addTags(sessionId);
}
}