Spring, background execution or on demand
I have a spring applicat开发者_如何转开发ion that uses org.springframework.scheduling.quartz.SimpleTriggerBean
to schedule execution of a method on a regular basis.
Sometimes, I want to call the same method "on demand". It will be trigger by an action on the GUI. Since the method that I want to execute takes a couple of sec, I don't want to block the user GUI until the execution finish. Moreover, I want to coordinate the "on demand" execution with the background thread (mutually exclusive).
Here's one approach:
- Create a Bean called Manager that use a TaskExecutor to schedule a Task. The Manager has a method Manager.scheduleTask()
- Both the background and the "on demand" threads will call the same method on the Manager (Manager.scheduleTask)
- The task runs in a synchronize method to assure that only one task is running.
I'm looking for more clever/cleaner solutions.
If you use Spring 3.0 or newer have a look at the Task Execution and Scheduling section of the reference doc.
It shows that there are two annotations:
@Scheduled
@Timer
The solution would be the same at least: having 3 methods:
private void doIt() {...}
@Scheduled(cron="0 0 0 * * MON-FRI")
public void doItEveryDay() {doIt();}
@Async
public void doItOnDemand() {doIt();}
But with these annotations, it would be easy to read and easy to understand why there are three methods.
You can use a SingleThreadExecutor
.
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.submit(<task>);
When your quartz job fires it can submit a task to the executor. Similarly, when your job is run manually, it can also submit a task to the executor. Since the ExecutorService only has a single thread, the task can only run once at a time. The other instance of the task will be queued up until the one which is currently running completes. You don't need to worry about manual synchronisation in this case.
精彩评论