I'm using Weld for CDI. I'm looking for a way to run a periodic thread which includes injected beans.
In main i want to create:
executorService.scheduleWithFixedDelay(new ExampleThread(), 1, 1, TimeUnit.SECONDS);
where ExampleThread is:
@ApplicationScoped
public class ExampleThread implements Runnable {
@Inject
private SomeBean someBean;
public ExampleThread() {}
@Override
public void run() {
someBean.do();
}
}
The issue is that once i create the ExampleThread using new() it makes its inner beans unusable. Is there a way to create the ExampleThread in a way that will work?
You can inject the bean this way:
executorService.scheduleWithFixedDelay(new ExampleThread(), 1, 1, TimeUnit.SECONDS);
and in the ExampleThread initialize the bean in the following way:
public class ExampleThread implements Runnable
{
private SomeBean someBean;
public ExampleThread()
{
this.someBean = CDI.current().select(SomeBean.class).get();
}
@Override
public void run() {
someBean.do();
}
}