Mar 01 2009
Defining a background Job to run periodically
One may need to run some task periodically in the background in Eclipse. This background task should run automatically and shouldn’t block user from regular usage of the application. My proposal for accomplishing this is using Eclipse Jobs API and org.eclipse.ui.startup extension-point.
- Adding org.eclipse.ui.startup extension:
- Dependencies:
- org.eclipse.ui
- org.eclipse.core.runtime
- Extension:
<?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.2"?> <plugin> <extension point="org.eclipse.ui.startup"> <startup class="tk.urbas.eclipse.urbanlife.Startup"></startup> </extension> </plugin>
- Dependencies:
- Implementing Job:
package tk.urbas.eclipse.urbanlife; 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; public class RefreshDataJob extends Job { public RefreshDataJob(String name) { super(name); } @Override protected IStatus run(IProgressMonitor monitor) { // Work to do in the background return Status.OK_STATUS; } }
- Scheduling Job to run periodically:
package tk.urbas.eclipse.urbanlife; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.ui.IStartup; public class Startup implements IStartup { private static final long STARTUP_DELAY = 5000; // 5 seconds delay for first run protected static final long JOB_INTERVAL = 60000; // Job should run every 60 seconds public void earlyStartup() { final Job updateJob = new RefreshDataJob("Refreshing data in the background"); updateJob.schedule(STARTUP_DELAY); updateJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { super.done(event); updateJob.schedule(JOB_INTERVAL); } }); } }
Let me know if you have any better solution for implementing this. All improvements, suggestions and comments will be greatly appreciated.