Dynamic Schedulers and Custom Cross-Server Schedule Lock
In this article, we gonna look into TaskScheduler and configure schedulers dynamically based on the database values.
Join the DZone community and get the full member experience.Join For Free
As part of java development, we always may run into a situation to configure a Job or Scheduler.
Quartz is one of the popular scheduling API.
In this article, we gonna look into TaskScheduler and configure schedulers dynamically based on the database values. This also includes simple mutex kind of logic, how can we avoid our scheduler running at a time when the app running as a cluster.
Before going into the topic, Let me give self inro. This is Venkatesh Rajendran, a full-stack software developer, and my key areas are Java, Spring framework (spring boot ), and hibernate, etc.. In the frontend , I'm not a big guy. I still learning. I have worked on jQuery and reactjs. And I'm exploring NodeJs as well. And This is my very first blog in my life :).
To manage and run our schedulers we need an ExecutorService. ThreadPoolTaskScheduler is one of the widely used SchedulingTaskExecutor. Let's create a bean of TaskScheduler using ThreadPoolTaskScheduler.
Let's move to the configurations part.
Since Schedulers are dynamically configured at run-time, We need to move our cron expressions and bean names that gonna run the job.
For these purposes, I have created an Entity called
In general, A scheduler should run a block of code. That's the purpose of the scheduler. So It's better to have an Interface that abstracts this operation. Also, this interface includes two more abstract methods.
resetLock are used for
Cross-Server Scheduler Locking.
Let's create an implementation for this interface.
Let's configure our scheduler,
Create an entry for SchedulerConfigEntity in db. Here I have a data.sql file that does the insert for us.
INSERT INTO scheduler_config VALUES
(1,'exampleSchedulerImpl','* * * * * *','OPEN');
And here our configuration class:
How do we enable Cross Server Scheduler lock, here we have introduced a column called
lock_ with default=
'OPEN'. When starting the job It will try to
acquire the lock and set to 'LOCKED' If not It should be running on another instance. When the job ends or fails, we should
reset the lock back to 'OPEN'. Let's check the JPA repository how it sets and resets the lock.
That's all. So we have an implementation for DynamicScheduler that reads the configuration from the database and a custom cross-server scheduler locking strategy. Please find the full implementation in my Git Repo.
Opinions expressed by DZone contributors are their own.