Sometimes you need to create an application to run a task in background at specific time of the day e.g uploading files to S3 at 11 am everyday.
I have used Dropwizard Sundial for scheduling jobs in the past. However, it does not support scheduling multiple cron jobs. You usually specify the cron expression as an annotation in the class that implements the
Job interface. In this blog post I am going to show how to implement a simple scheduler application using Dropwizard and Quartz 2.
You need to add the following dependencies in your pom.xml.
First we will implement a class named
MyJob which implements the quartz
Job interface. As you can see from the below code snippet,
MyJob class has a constructor which takes a parameter name.
MyJobFactory class which implements the quartz
JobFactory interface. This class has a constructor which takes a
SchedulerCongifuration as a parameter and instantiate
MyJob object using the name value from the configuration. This class is responsible for providing any new instances of Jobs.
SchedulerApplication#runmethod we create a
MyJobFactory and then create a
SchedulerFactory. We get the
Scheduler object from
SchedulerFactory class. We then set the
JobFactory object we created on line 14 to a scheduler and start the scheduler.
We then create a new instance of
JobDetail and create a simple
Trigger which runs every 30s. We then parse the cron triggers (comma separated string) and create a list of
CronTrigger objects. We then add the simple trigger we have created to this list
We then create a
Map<JobDetail, List<Trigger>> jobDetailMap and populate it with the job and triggers. We then schedule the jobs by setting
I have enjoyed using Quartz 2 and I would recommend if you want to run multiple cron jobs. You can find the example code used in this post here.
Update, 17 June 2006: I’ve written the demo code in a hurry, so please excuse the code quality 😉
If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.