0

I'm using spring 5 scheduler in my web app & I need to set my fixedrate at run time, so I'm using ServletContextListener with @WebListener annoated. In servletcontext class I'm using TaskScheduler scheduler.setFixedAtRate(<Runnable>, <Get value from DB>, <time period>); I had annotated my service class Scheduler configured successfully & executing on time. But problem is getting @Autowired my services in scheduled class, they are not binding. While other business logic @Autowired working successfully.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Waqas Baig
  • 79
  • 2
  • 9
  • can you use the `@Scheduled` annotation? (http://www.baeldung.com/spring-scheduled-tasks) – blurfus May 24 '18 at 18:47
  • No I can't because request is that to add fixedrate at run time. I got the answer from some googling, problem is that I'm using ServletContextLisnter, so contextlistener loaded before application start, that's why my scheduled class @Autowired is not working properly. ochi: do you have any other idea besides ServletContextListener? Because I need to scheduled at run time but after application deployed or loaded. Is there better approach for this in spring or JEE??? – Waqas Baig May 24 '18 at 18:57
  • I am sorry I am not understanding, the fixed rate is to be set at runtime or at startup/load time? – blurfus May 24 '18 at 19:00
  • If it is at load time, you can do something like `@Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")` where the value comes from your properties file – blurfus May 24 '18 at 19:03
  • ok let me elaborate you. I have my milliseconds value in database table, so I need to scheduler on fixedrate of value exists in database table, that's why I need to implement a class which one scheduled after application startup. Now you got my point? – Waqas Baig May 24 '18 at 19:11
  • Ochi I got an answer from some googling, I can use @EventListener for this, but little confused about classes scheduled after application startup or it will execute during applicationcontext loading. Do you have any idea? – Waqas Baig May 24 '18 at 19:13
  • Posible duplicate of https://stackoverflow.com/questions/48440826/setting-value-for-config-of-spring-scheduled-from-database – blurfus May 24 '18 at 21:08
  • Ochi not working for me this sample. – Waqas Baig May 25 '18 at 07:30

1 Answers1

0

It's because ServlerContextListener mostly isn't managed by Spring. It's well explained in here: Spring @Autowired annotation doesn't work in Java TimerTask

Mafuj Shikder
  • 141
  • 1
  • 8