Thursday, April 9, 2015

Eclipse Jobs framework best practice: Handling the long running background jobs while Eclipse shutdown

How to handle background jobs which are running silently for a long time during the Eclipse shutdown ?

Solution would be to cancel all the jobs before before plugin stops,so that jobs won't complain about the other resources availablity. If we don't do this, some times we can get some null pointer issues in the log.

In Plugin Activator class, just invoke Job.getJobManager().cancel(jobName);


import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.osgi.framework.BundleContext;

public abstract class AbstractJob extends Job
{

private String jobFamilyName;

public AbstractJob(String name, String jobFamilyName)
{
super(name);
this.jobFamilyName = jobFamilyName;
}

@Override
public boolean belongsTo(Object family)
{
return this.jobFamilyName.equals(family);
}
}

Your Actual Job Implementation:

Job coreJob = new AbstractJob("Collecting assets", "ASSETS_FAMILY")
{

@Override
protected IStatus run(IProgressMonitor monitor)
{
//TODO: some long work job

return Status.OK_STATUS;
}
};

coreJob.schedule();


In Activate Class:

public void stop(BundleContext context) throws Exception {
plugin = null;
Job.getJobManager().cancel("ASSETS_FAMILY");
super.stop(context);
}

This will cancel all the jobs who's family name is ASSETS_FAMILY.


No comments:

Post a Comment