Skip to content

Canceling Jobs

mendhak edited this page Jul 4, 2015 · 6 revisions

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 cancels 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.

Basic example

You can set a tag in the Job's constructor,

super(new Params(1).requireNetwork().persist().addTags("PICKME"));

You can then cancel the job from elsewhere using

jobManager.cancelJobsInBackground(null, TagConstraint.ANY, "PICKME");

Canceling Jobs of an Activity

Here is an example on how you could cancel all jobs created for an Activity when it becomes invisible. This sample uses onStart and onStop, but you could also use onCreate and onDestroy.

public class BaseActivity extends Activity {
  ...
  // a random string identifier that is generated when Activity becomes visible
  private String sessionId; 
  // preferably injected
  private JobManager jobManager; 

  public String getSessionId() {
    return sessionId;
  }

  @Override
  protected void onStart() {
    super.onStart();
    sessionId = UUID.randomUUID().toString();
  }

  @Override
  protected void onStop() {
    super.onStop();
    // this MUST be async to avoid blocking the main thread
    jobManager.cancelJobsInBackground(null, TagConstraint.ANY, sessionId);
  }
}

Now, you can create an ActivityBoundJob which takes BaseActivity as a constructor parameter and automatically binds itself to the given activity.

abstract class ActivityBoundJob extends Job {
  public ActivityBoundJob(BaseActivity activity, Params params) {
    super(params.addTags(activity.getSessionId()));
  }
}