user2270439
user2270439

Reputation: 67

Spring setting application property programmatically

Basically I have some cron - properties in my application.yml:

B = 0 11/15 * * * ?

I have a bean RefresherB which has

@Scheduled(cron = "${B}")
public void refresh() {
    //Refreshing
}

I also have a rest endpoint from which I want to update this B property

@RequestMapping("schedule")
public boolean changeRefreshSchedule(@QueryParam("cron") String expression){

Where I want to update the B property so that the RefresherB bean also gets the update. How would I go about doing this? I do not want to change the application.yml file only update the value for runtime.

Upvotes: 2

Views: 1349

Answers (1)

luk2302
luk2302

Reputation: 57184

Looking at the source code of ScheduledAnnotationBeanPostProcessor my assumptions seems to be correct: that cannot be done easily.

Because the methods annotated with @Scheduled are processed once at application context startup, the values of the annotation are parsed, tasks are scheduled and after that the annotation are never touched / looked at again. That means even if you could change the value of the annotation which is actually difficult already spring would not know about your changed value.

Of course you can write your own custom ScheduledAnnotationBeanPostProcessor which could handle that but that would be a lot of work. Other options include what is written in How to change Spring's @Scheduled fixedDelay at runtime which would still require quite a bit of work on your part. There is no out of the box solution.

What you can do of course is let spring trigger your method far too often and have some custom logic in place which determines when to actually do something.

Upvotes: 2

Related Questions