如何在石英上下文中执行 db/jpa 操作?

How to execute db/jpa operations inside quartz context?

我有这项服务正在安排任务:

@ApplicationScoped
public class PaymentService {

    @Transactional
    public Payment scheduleNewPayment(Payment payment) throws ParseException, SchedulerException {
        Payment.persist(payment);
        JobDetail job = JobBuilder.newJob(PaymentJob.class)
                .withIdentity(String.format("job%d", payment.id), "payment-job-group")
                .build();
        Date parsed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(payment.dueDate);
        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity(String.format("trigger%d", payment.id), "trigger-group")
                .startAt(parsed)
                .forJob(job)
                .build();
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
        return payment;
    }

}

而这份工作:

@ApplicationScoped
public class PaymentJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println(Payment.count());
    }

}

但是我无法在作业上下文中执行数据库操作(jobExecutionContext.getScheduler().getContext() 顺便说一下,它是空的)。

我是 运行 我的 quarkus 应用,hibernate 操作来自 Hibernate Panache,Scheduler 是 quartz。

首先,您应该使用底层托管 Quartz Scheduler 实例:@Inject org.quartz.Scheduler(我想您使用的是 quarkus-quartz 扩展)。

另一个 "problem" 是默认的 Quartz 作业工厂简单地调用 new PaymentJob() 所以没有 injection/initialization 被执行。 Quarkus 仅将自定义工厂用于为使用 @Scheduled 注释的方法生成的作业。如果您不需要注入,那么只需从 PaymentJob class.

中删除多余的 @ApplicationScoped

最后,您需要手动激活所有必要的 CDI 上下文。很可能需要请求上下文。您可以复制以下代码段:https://github.com/quarkusio/quarkus/blob/master/extensions/arc/runtime/src/main/java/io/quarkus/arc/runtime/BeanInvoker.java#L14-L24 到您的 execute() 方法中。

jobExecutionContext.getScheduler().getContext() is null by the way

这真的很奇怪。 exception/error 你实际得到了什么?