Reputation: 41
I have a scheduler(using @Scheduler) running between 7 to 9 PM for every 15 mins. It looks for a file every 15 mins. If the file is found then the scheduler should stop for today and run next day again. How to achieve this in spring boot?
Upvotes: 1
Views: 2144
Reputation: 42441
Probably the easiest way is to implement it at the level of business logic. Spring provides a way to run a periodic task, that's true, but it can't stop the job for some time if a business case is met (the file is found).
Having said that, you could implement the scheduled job as follows:
@Component
public class MyScheduledJob {
private LocalDateTime runNextTime = null;
private boolean isFileFound = false;
@Scheduled(/**here comes your original cron expression: 7 am to 9 pm with an interval of 15 minutes as you say **/)
public void runMe() {
if(isFileFound && LocalDateTime.now().isBefore(runNextTime)) {
// do not run a real job processing
return;
}
isFileFound = checkWhetherFileExists();
if(isFileFound) {
runNextTime = calculateWhenDoYouWantToStartRunningTheActualJobProcessingNextTime();
}
... do actual job processing... Its not clear from the question whether it should do something if the file is not found as well, but I'm sure you've got the point ...
}
}
Since the bean is a singleton you can safely create a state for it, no-one won't change that state anyway.
Upvotes: 3
Reputation: 357
You can do something like this. You can write your logic for checking files inside this method.
@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void scheduleFixedRateWithInitialDelayTask() {
long now = System.currentTimeMillis() / 1000;
System.out.println(
"Fixed-rate task with one-second initial delay - " + now);
}
See this for more details.
Upvotes: 0