Last changed: Nov 06, 2008 22:54 by
Uwe Schaefer Labels:
guice,
quartz,
java
whenever you have any need for cron-like functionality within your java application, Quartz is the obvious chose for quite a long time now.
i did not need much of what quartz had to offer, so i went with a home-grown implementation. why? the fear of having to integrate a good, but feature-rich framework, you really don´t need most of the time.
well, that was a mistake. Quartz offers a very easy and stable API and a bunch of good helper classes, designed after common usecases. but there is one more important quality that every good framework nowadays has to have: it is non-intrusive in regards to creating its objects.
my 'special' case was integration with guice, so that i could use @Inject to implement my jobs. i was pleased to learn that it was as easy as this:
final class GuiceJobFactory implements JobFactory
{
private final Injector guice;
@Inject
public GuiceJobFactory(final Injector guice)
{
this.guice = guice;
}
@Override
public Job newJob(final TriggerFiredBundle bundle) throws SchedulerException
{
JobDetail jobDetail = bundle.getJobDetail();
Class jobClass = jobDetail.getJobClass();
return (Job) guice.getInstance(jobClass);
}
}
this example class is used to delegate the actual object creation to Guice. this makes Quartz integration a no-brainer, whatever environment you need it in.
all you have to do then is create the Scheduler accordingly:
public class Quartz
{
private final Scheduler scheduler;
@Inject
public Quartz(final SchedulerFactory factory, final GuiceJobFactory jobFactory) throws SchedulerException
{
scheduler = factory.getScheduler();
scheduler.setJobFactory(jobFactory);
scheduler.start();
}
public final Scheduler getScheduler()
{
return scheduler;
}
public void shutdown()
{
try
{
scheduler.shutdown();
}
catch (SchedulerException e)
{
}
}
}
and bind it all together like:
public class QuartzModule extends AbstractModule
{
@Override
protected void configure()
{
bind(SchedulerFactory.class).to(StdSchedulerFactory.class).in(Scopes.SINGLETON);
bind(GuiceJobFactory.class).in(Scopes.SINGLETON);
bind(Quartz.class).in(Scopes.SINGLETON);
}
}
what did i learn from that?
frameworks are easy to integrate as long as they do not necessarily claim to manage the lifecycle of (even their own) objects unless absolutely necessary.
want another proof? see Wicket: Application.newSession(...)