Big Picture & Problem:
Cron jobs are a type of automated task scheduler that execute tasks at scheduled time which is fixed and needs to be provided before application starts up.
Many times we come across situations where we need to dynamically schedule tasks that needs to be executed periodically.
In this blog, we will be building
a monitoring tool that can track uptime of any web
site. The name of the tool is UMT. (Uptime Monitoring Tool)
Solution:
For scheduling tasks we can use simple Spring Scheduler or frameworks like quartz. Spring Scheduler is simpler and more lightweight, making it suitable for smaller applications with simpler scheduling requirements. As in our case we need to periodically check for website health at regular interval we need quartz because it helps in more complex scheduling, job persistence, clustering, or job chaining features. It will help us in scaling our application as per need.
Keeping that basic requirement in our mind, let us come up with a basic database design that may look like this -
Entity_Tables
We have a check table to store the information like URL to be checked along with the periodic frequency for it to be performed. We also have a health table to store the health status against a check that is getting executed.
Configuration
:
To configure quartz in your spring application you need to add the following dependency in your build.gradle or pom.xml file.
implementation 'org.springframework.boot:spring-boot-starter-quartz'
implementation 'com.mchange:c3p0:0.9.5.5'
and in you main/resources/application-properties file add
spring.quartz.job-store-type=jdbc
spring.quartz.jdbc.initialize-schema=always
This will create the quartz schema in the database.
We will provide the quartz properties using quartz.properties file.
#Quartz
org.quartz.scheduler.instanceName = SampleJobScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.idleWaitTime = 10000
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 4
org.quartz.threadPool.threadPriority = 5
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.