In most common cases, the BC code is called from a managed bean (MB) whose execution was originated by an HTTP request made by the web browser. In these cases, there is an active RequestContext that allows you to use @Inject
.
The problem is that the job runs on a separate thread, which does not have access to a context. To resolve this, you must pass the BC to the job and, within the job, create a request context.
The class that creates the job must inject the BC and a RequestContext; when creating the job, these objects must be passed to the job through a JobDataMap:
@BusinessController
public class Agendador {
@Inject
private MinhaClasseBC meuObjetoBC;
@Inject
private BoundRequestContext requestContext;
public void agendaJob() throws SchedulerException {
JobDataMap jobData = new JobDataMap();
jobData.put("requestContext", requestContext);
jobData.put("bc", meuObjetoBC);
JobDetail job = newJob(ClasseDoJob.class)
.withIdentity("id", "grupo")
.setJobData(jobData)
.build();
// aqui vem o código da trigger e do agendamento
}
}
The job class then takes these objects and creates the context before calling the BC (and destroying after the call):
public class ClasseDoJob implements Job {
@Override
public void execute(JobExecutionContext jobContext) throws JobExecutionException {
JobDataMap jobData = jobContext.getJobDetail().getJobDataMap();
BoundRequestContext ctx = (BoundRequestContext)jobData.get("requestContext");
MinhaClasseBC bc = (MinhaClasseBC)jobData.get("bc");
ctx.associate(new HashMap<String, Object>());
ctx.activate();
bc.metodoQueFazAlgumaCoisa();
ctx.invalidate();
ctx.deactivate();
}
}