user5620472
user5620472

Reputation: 2892

How can I make init method before called @Scheduled method in spring class?

This is my java class

@Component
public class ReportTasckScheduler {
@PostConstruct
    public void init() {
        List<ReportTasck> allByStatus = reportTasckRepository.findAllByStatus(1);
        if (allByStatus.isEmpty()) return;
        for (ReportTasck allByStatu : allByStatus) {
            allByStatu.setStatus(0);
            allByStatu.setStartDate(new Date());
            reportTasckRepository.save(allByStatu);
        }
    }

    @Scheduled(fixedRate = 5000)  //раскоментировать для шедлинга
    public void startSchedule() throws IOException, NurException {
        //code
    }
}

Can I be sure that init() wiil called before startSchedule() always? if not, how do I make my check is always called during initialization, before the first start startSchedule()?

Upvotes: 0

Views: 5081

Answers (2)

Roland Weisleder
Roland Weisleder

Reputation: 10531

The PostConstruct will be invoked during the bean initialization. The Scheduled method will be invoked after the bean was initialized. Please note that this bean exists only once in your Spring context, so that PostConstruct will be invoked only during startup.

See also this answer: Will a method annotated with @PostConstruct be guaranteed to execute prior to a method with @Scheduled within the same bean?

Upvotes: 3

PaulNUK
PaulNUK

Reputation: 5249

Don't use the annotation to schedule the task, inject a TaskScheduler into your class and then schedule the task programamticaly at the end of your init method

e.g.

@Inject
private TaskScheduler taskScheduler;

....

then

taskScheduler.scheduleAtFixedRate(this,5000);

Upvotes: -1

Related Questions