Skip to content

Instantly share code, notes, and snippets.

@Jire
Created July 24, 2011 03:54
Show Gist options
  • Save Jire/1102212 to your computer and use it in GitHub Desktop.
Save Jire/1102212 to your computer and use it in GitHub Desktop.
Used to schedule and manage Job implementations.
package us.ironbase.job;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Used to schedule and manage {@link Job} implementations.
*
* Each <tt>Scheduler</tt> maintains a registry of {@link Trigger}s
* which jobs may be associated to. When these triggers are activated
* the business logic of all related jobs are executed.
*
* @author Thomas Nappo
*/
public class Scheduler {
/**
* This internal map is utilized to associate {@link Job} implementations
* with {@link Trigger}s so that they may be executed at
*/
private final Map<Trigger, Job> registry = new HashMap<>();
/**
* This internal executor service is used to schedule {@link Job}s.
*/
private final ScheduledExecutorService service;
/**
* Constructs a new scheduler.
* @param nThreads The number of threads to provide to {@link #service}.
*/
public Scheduler(int nThreads) {
service = Executors.newScheduledThreadPool(nThreads);
}
/**
* Constructs a new single-threaded scheduler.
*/
public Scheduler() {
this(1);
}
/**
* Schedules a {@link Job} by constructing a {@link JobLegacy}
* which can be used to schedule the job's logic to be ran.
* @param job The <tt>Job</tt> implementation which handles the business logic.
* @return The product <tt>JobLegacy</tt> which should be utilized to configure
* the job and then truly schedule it to this scheduler.
*/
public JobLegacy schedule(Job job) {
return new JobLegacy(job, this);
}
/**
* Schedules a {@link JobLegacy} by using it's attributes for a
* {@link ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)}
* call.
* @param jobLegacy The <tt>JobLegacy</tt> which contains the configured attributes needed
* to use the fucntionality for scheduling provided by the {@link #service}.
*/
protected void schedule(final JobLegacy jobLegacy) {
service.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
jobLegacy.getParent().execute();
}
}, jobLegacy.getRate(), jobLegacy.getRate(), TimeUnit.MILLISECONDS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment