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.
Related
It is possible to configure custom executor using ExecutorConfig, e.g.:
Config config = new Config();
config.getExecutorConfig("my-custom-executor").setPoolSize(40).setName("my-executor");
This will finally create some java.util.concurrent.ThreadPoolExecutor child.
But how can I specify customly created java.util.concurrent.ExecutorService implementation as some named executor in Hazelcast?
Creating a custom j.u.c.ExecutorService managed by Hazelcast is not possible at the moment (current latest GA version is 3.12.5 and 4.0 is about to be released). All executors share the same cached thread-pool using separate task queues per custom executor (see CachedExecutorServiceDelegate). And this shared thread pool is an instance of j.u.c.ThreadPoolExecutor.
I think it should be fairly easy to add this as a new feature. You can create an issue at Issue Tracker or better send a pull request with an implementation.
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?
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 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
I want to have a work queue that behaves almost exactly like ruby's sidekiq(it doesn't need to use Redis, but it can - I just can't use ruby - not even Jruby). Basically I want to be able to create jobs that runs with some parameters and a worker pool executes the jobs. The workers are going to use hibernate to do some work, so I think that Spring integration could make things easier.
Spring Integration has Redis Queue inbound and outbound channel adapters.
The inbound message-driven adapter doesn't currently support concurrency; we worked around that in Spring XD with a composite adapter that wraps a collection of RedisQueueMessageDrivenEndpoint.
Or you could use RabbitMQ; the Spring Integration adapter for it does support concurrency.
EDIT
The bus was extracted to a sub project within that repo.
Spring Framework has ThreadPoolTaskExecutor. You could use it in your class as follows.
#Autowired
ThreadPoolTaskExecutor executor;
ThreadPoolTaskExecutor has properties needed to be set before it is put to use. PostConstruct will be executed after the dependency injections, so we can set the properities of ThreadPoolExecutor there.
#PostConstruct
public void init() {
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
}
Then you can start using executor as follow
executor.execute(new EmailtoCustomerTask("zhw#gmail.com"));
The only requirement needed to become a task is to implement the Runnable interface.
private class EmailtoCustomerTask implements Runnable