Java: Build your own JobManager

So often I see developers turn to open source to implement job management.  These are often far more advanced than what many people really need in their Java applications.  Sure there are times when it is needed and called for, however many times that is not the case.  Today I will show you a JobManager that will satisfy many needs.  First off let’s look at the basic requirements.

  1. It should use a ThreadPool
  2. Manage Jobs that need to run as soon as possible.
  3. Schedule Jobs to run at a later time.
  4. Manage services that should be enabled to run full time.

Really this is more about managing threads than managing jobs.

First let’s look at the JobManager class.

As you can see here we have a singleton, that uses the JobManager.getInstance() to retrieve the global instance.  You can adjust the SCHEDULED_THREADS, PROCESSOR_RESERVE, and PROCESSOR_MULTIPLIER based on your system.  In fact you can make them easily configurable if you wish.

We have the following methods for running Jobs:

  • submit(Job job)
  • executeJob(Job job)

In addition we have the following for scheduling Jobs to run:

  • schedule(Job job, long delay, TimeUnit unit)
  • scheduleAtFixedRate(Job job, long initialDelay, long period, TimeUnit unit)
  • scheduleWithFixedDelay(Job job, long initialDelay, long delay, TimeUnit unit)

We also need a way to run our services:

  • createService(final String name, final AbstractService service)

Now let’s take a look at the Job class.  We need to be able to tie multiple Jobs together.  So we will add a Pre & Post Job processing, we’ll make it possible to override methods for this.

So you can override the preProcess() and postProcess() methods to perform any processing you wish to do before and after the main processing and processing of the sub-Jobs.  In addition you can add Jobs that are executed after this Job’s process is completed.

Now let’s look at a service.  It needs to be able to shutdown easily and execute on it’s own thread entirely.

Implement the following methods on your Service.

  • start() – any steps necessary to start your Service.
  • stop(final int delay) – steps necessary to stop your service.
  • service() – main loop of your thread that needs to stay executing.
  • Ghostprogrammer
  • I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: