Issue with Quartz and Spring Boot - java

So I have a technical challenge I need help with.
A large scale project is using a Quartz scheduler to schedule a job to run every night at 9.
The Job that is scheduled, however needs to read values from property files, get some beans using auto-wiring etc.
When I used #Autowired and #Value annotations, I found the values to be null.
The issue is that Quartz creates JobDetail objects using newJob() outside the spring container. As can be seen in the below code.
JobKey jobKey = new JobKey("NightJob", "9-PM Job");
JobDetail jobDetail = newJob(NightJob.class).withIdentity(jobKey)
.usingJobData("Job-Id", "1")
.build();
The jobDetail object which wraps NightJob thus cannot access property files or beans using spring.
Here is my NightJob class
public class NightJob implements Job{
//#Value to read from property file; here
//#Autowired to use some beans; here
#Override
public void execute(JobExecutionContext context) throws JobExecutionException{
}
}
I scanned Stack Overflow and shortlisted several solutions. I also read through the comments and listed the top counter-comments.
Suggestion 1: Get rid of Quartz and use Spring Batch due to its good integration with Spring Boot
Counter argument 1: Spring Batch is overkill for simple tasks. Use #Scheduled
Suggestion 2: Use #Scheduled annotations and cron expressions provided by spring
Counter argument 2: Your application will not be future ready if you remove Quartz. Complex scheduling may be required in the future
Suggestion 3 : Use the spring interface ApplicationContextAware.
Counter argument 3: Lots of additional code. Defeats the simple and easy concept of Spring boot
Is there a simpler way in Spring Boot to access property file values and autowire objects in a class that implements a Quartz job (In this situation , the NightJob class)

As written in the comments, Spring supports bean injection into Quartz jobs by providing setter methods: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-quartz.html

Related

Batch 4.0.1 - job starts but jobParametersValidator is null

I am integrating Spring Batch into an existing Spring webapp and have created three simple jobs as a learning process. Then I created a set of ancestor classes for jobs/readers/writers that can be used to migrate our old batch jobs easily.
We intend to run the jobs asynchronously from within Tomcat as separate threads. I have created a UI to manage and start/stop them.
I have a class annotated with #Configuration and #EnableBatchProcessing which does the job of setting up all the global classes for batch mode; it also then scans the base package for all our jobs for specific ancestor class. Then it suffixes each class name for the corresponding *Factory class, does a getBean for that class and uses it to register each job:
Job job = jobFactory.createInstanceForRegistration();
jobRegistry.register(new ReferenceJobFactory(job));
The createInstanceForRegistration method uses applicationContext.getBean to get the instances of the job/read/writer classes to put the job and steps together and then finally:
((SimpleJob)job).setSteps(steps);
return job;
In the UI, the jobs are listed and I should be able to start them. But when I do:
batchAuditId = jobOperator.start(jobName, parameters);
Suddenly, a NPE is thrown from w/i AbstractJob/execute # line 298:
jobParametersValidator.validate(execution.getJobParameters());
because jobParametersValidator is null - despite the fact that it is initialized with a default in the class itself:
private JobParametersValidator jobParametersValidator =
new DefaultJobParametersValidator();
More to the point, the job class constructor has code that sets several items, including the override of the validator:
super(BATCH_NAME, BATCH_TYPE_CODE, BATCH_FUNCTION, BATCH_PROCESS_AREA);
setLogger(LoggerFactory.getLogger(CustomJob.class));
getLogger().debug("constructed: {}", this.toString());
setParametersRequired(Boolean.TRUE); // this job requires parameters
setRestartable(Boolean.TRUE);
setJobParametersValidator(new CustomJobParametersValidatorImpl());
During deployment, when Spring creates all the classes, I can step through the code and the override validator is created and set for that job.
Yet when jobOperator.start executes, the NPE is thrown.
I can find no reason for this. It is almost like jobOperator.start somehow creates a new instance of the job class in a way that doesn't use the existing instance or my custom constructor.
Can anyone explain what is going on?

Java - Get all the implementations of an interface available in client package

I am developing one task scheduler which triggers the tasks in parallel using executor service. I want to make my task scheduler as generic and no code change/less code change in scheduler code base whenever any new type of task is added.
My tasks (mostly client package) can be of any type which basically just accepts particular request and execute the tasks.
To do this I am exposing interface (say ITask) which must be implemented by tasks (which will be on some other app/package) and that will be having one implementation method say example
doTask(IRequest request);
So the use case is if any clients who wants to trigger their job using my scheduler framework/API, just need to add my package in their dependency and rest (those are, getting the list of task classes which implements ITask > schedule it using executor service > retry failed tasks > finally provide the entire tasks status) should be taken care by my schedular API.
What is the optimal way to do this. I am thinking of solution how Junit gets its #Test methods (based on annotation) of client whoever adds Junit dependency in his package, similarly I want get classes based on interface.
You have tagged this question with Spring, but you don't mention anywhere in the question that you are using the Spring framework. This answer makes a few assumptions:
You are using Spring Framework
The implementations of your desired interface have been configured as Spring Beans
If you get access to the ApplicationContext (see the interface ApplicationContextAware), you can use it to look up Spring beans of a certain type. It would look something like this:
Map<String, ITask> beans = appContext.getBeansOfType(ITask.class);
This method returns a map with the key being the bean identifier and the value being the instance of the bean itself. From there, you could loop through the values and add them to your job scheduler.
Alternatively
If you do not want the requirement of having to configure each ITask implementation as a Spring bean, you could use Spring's ClassPathScanningCandidateComponentProvider (a mouthful, I know).
This is a nifty tool that allows you to scan base packages to find bean "candidates". However, in your case, you could use it to find ITask candidates. Clients to your library could configure the base scan packages which you would use to scan:
private String configuredListOfBasePackages;
public void someMethod () {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AssignableTypeFilter(ITask.class));
Set<BeanDefinition> iTaskCandidates = scanner.findCandidateComponents(configuredListOfBasePackages);
// do stuff with the bean definitions
}
This method is obviously a bit more dangerous as it require you to be able to construct a new instance of every candidate you find. As such, this is not the ideal solution.

how to set cron expression dynamically with database values for different jobs in spring 4

I want to configure scheduler in my application where I have to set cron expression with database values dynamically. When application starts, a method should fetch the database values in set them in cron expression for a particular job. Please help me with this. I am all new to quartz scheduler, spring scheduler concepts
You can very well use TaskScheduler class of Spring Scheduling in this case.
Please have a look at the class definition:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/TaskScheduler.html
scheduler.schedule(runnableTask, new CronTrigger(cron, TimeZone.getTimeZone(timezone)));
You can create a runnable task as follows:
class RunnableTask implements Runnable {
#Override
public void run() {
//
}
}
While creating a cron trigger, you can load cron expression from database.
You may want to look at this answer. https://stackoverflow.com/a/4499229/82632
Basically you need to autowire TaskScheduler class then programmatically add jobs with it.

How to launch a Spring Batch job after startup?

How can I run a job configured using Spring-Batch right after application startup?
Currently I'm specifying an exact time using cron job, but that requires to change the cron every time I restart the application:
#JobRegistry, #Joblauncher and a Job.
I execute the job as follows:
#Scheduled(cron = "${my.cron}")
public void launch() {
launcher.run(job, params);
}
Checking aroud Spring code I have found SmartLifecycle
An extension of the Lifecycle interface for those objects that require
to be started upon ApplicationContext refresh and/or shutdown in a
particular order. The isAutoStartup() return value indicates whether
this object should be started at the time of a context refresh.
Try creating a custom bean implementing SmartLifecycle and setting autoStartup; when this custom bean start method is invoked launch your job.
A few options that I can think of on the places to put your startup logic:
.1. In a bean #PostConstruct annotated method, reference is here - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-postconstruct-and-predestroy-annotations
.2. By implementing an ApplicationListener, specifically for either ContextStartedEvent or ContextRefreshedEvent. Reference here - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#context-functionality-events

looking for persistent timers for a spring application

I'm looking for a lib that allow me to do
define a worker that will be invoked once on a specific time in the future (not need the re-schedule / cron like featrure) i.e. a Timer
The worker should accept a context which withe some parameters / inputs
all should be persistent in the DB (or file) the worker
worker should be managed by spring -- spring should instantiate the worker so it can be injected with dependencies
be able to create timers dynamically via API and not just statically via spring XML beans
nice to have:
support a cluster i.e. have several nodes that can host a worker. each store jobn in the DB will cause invokaction of ONE work on one of the nods
I've examined several alternatives none meets the requirements:
Quartz
when using org.springframework.scheduling.quartz.JobDetailBean makes quartz create your worker instance (and not by spring) so you can't get dependecy ijection, (which will lead me to use Service Locator which I want to avoid)
while using org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean you can't get a context. your Worker expose one public method that accepts no arguments.In addition when using MethodInvokingJobDetailFactoryBean you can't use persistence (form the Javadoc)
Note: JobDetails created via this FactoryBean are not serializable and thus not suitable for persistent job stores. You need to implement your own Quartz Job as a thin wrapper for each case where you want a persistent job to delegate to a specific service method.
Spring's Timer and simple JDK Timers does not support the persistence / cluster feature
I know I can impl thing myself using a DB and Spring (or even JDK) Timers but I prefer to use an a 3r party lib for that.
Any suggestions?
If you want to create the job details to generate triggers/job-details at runtime and still be able to use Spring DI on your beans you can refer to this blog post, it shows how to use SpringBeanJobFactory in conjunction with ObjectFactoryCreatingFactoryBean to create Quartz triggering objects at runtime with Spring injected beans.
For those interested in an alternative to Quartz, have a look at db-scheduler (https://github.com/kagkarlsson/db-scheduler). A persistent task/execution-schedule is kept in a single database table. It is guaranteed to be executed only once by a scheduler in the cluster.
Yes, see code example below.
Currently limited to a single string identifier for no format restriction. The scheduler will likely be extended in the future with better support for job-details/parameters.
The execution-time and context is persistent in the database. Binding a task-name to a worker is done when the Scheduler starts. The worker may be instantiated by Spring as long as it implements the ExecutionHandler interface.
See 3).
Yes, see code example below.
Code example:
private static void springWorkerExample(DataSource dataSource, MySpringWorker mySpringWorker) {
// instantiate and start the scheduler somewhere in your application
final Scheduler scheduler = Scheduler
.create(dataSource)
.threads(2)
.build();
scheduler.start();
// define a task and a handler that named task, MySpringWorker implements the ExecutionHandler interface
final OneTimeTask oneTimeTask = ComposableTask.onetimeTask("my-onetime-task", mySpringWorker);
// schedule a future execution for the task with a custom id (currently the only form for context supported)
scheduler.scheduleForExecution(LocalDateTime.now().plusDays(1), oneTimeTask.instance("1001"));
}
public static class MySpringWorker implements ExecutionHandler {
public MySpringWorker() {
// could be instantiated by Spring
}
#Override
public void execute(TaskInstance taskInstance, ExecutionContext executionContext) {
// called when the execution-time is reached
System.out.println("Executed task with id="+taskInstance.getId());
}
}
Your requirements 3 and 4 do not really make sense to me: how can you have the whole package (worker + work) serialized and have it wake up magically and do its work? Shouldn't something in your running system do this at the proper time? Shouldn't this be the worker in the first place?
My approach would be this: create a Timer that Spring can instantiate and inject dependencies to. This Timer would then load its work / tasks from persistent storage, schedule them for execution and execute them. Your class can be a wrapper around java.util.Timer and not deal with the scheduling stuff at all. You must implement the clustering-related logic yourself, so that only one Timer / Worker gets to execute the work / task.

Categories

Resources