I have a spring application 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:
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@TimerThe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With