Scheduling in Helidon Microprofile

91 views Asked by At

I am trying to configure a scheduler in Helidon Microprofile. I am trying to get the IntialDelay and value for FixedRate from configuration file but it doesn't seem to work. I am providing all the different ways I have tried. Please help me resolve this issue in best possible way. Thank you.

In the below code, I am expecting the constructor to be called and first and initialise the TaskScheduler(). But that is not happening. The taskScheduler is not getting scheduled.

@ApplicationScoped
public class TaskScheduler {
    private final Long initialDelay;
    private final Long fixedRate;
    private static final Logger LOGGER = Logger.getLogger(TaskScheduler.class.getName());

    @Inject
    public TaskScheduler() {
        org.eclipse.microprofile.config.Config config = ConfigProvider.getConfig();
        this.initialDelay = config.getOptionalValue("scheduler.initialDelay", Long.class).orElse(2L);
        this.fixedRate = config.getOptionalValue("scheduler.fixedRate", Long.class).orElse(2L);
       ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
       scheduler.scheduleAtFixedRate(this::taskScheduler, this.initialDelay, this.fixedRate, TimeUnit.SECONDS);
    }
    public void taskScheduler()  {
        LOGGER.info("Running tasks: ");

    }
}

I have tried to pass ConfigProperty as constructor parameters as below code, but I get this exception Exception in thread "main" org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Long with qualifiers @Default

@Inject
public TaskScheduler(
        @ConfigProperty(name = "scheduler.initialDelay") Long delay,
        @ConfigProperty(name = "scheduler.fixedRate") Long rate
                     ) {
    this.initialDelay = delay;
    this.fixedRate = rate;

   ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
   scheduler.scheduleAtFixedRate(this::taskScheduler, this.initialDelay, this.fixedRate, TimeUnit.SECONDS);
}

I have also tried to use @PostConstruct but this doesn't get called at all.

 @PostConstruct
 public void postConstruct() {
     LOGGER.info("Running tasks: ");
     Config config = ConfigProvider.getConfig();
     long initialDelay = config.getOptionalValue("scheduler.initialDelay", Long.class).orElse(2L);
     long fixedRate = config.getOptionalValue("scheduler.fixedRate", Long.class).orElse(2L);
     ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     scheduler.scheduleAtFixedRate(this::taskScheduler, initialDelay, fixedRate, TimeUnit.SECONDS);
 } 
0

There are 0 answers