gpt4 book ai didi

java - 避免 Quartz 每次都创建新实例

转载 作者:行者123 更新时间:2023-11-30 02:03:55 25 4
gpt4 key购买 nike

Quartz 每次都会通过 JobBuilder 创建该类的新实例

JobBuilder.newJob(MyJob.class)

但是,我只想要一个 MyJob 实例,并且只从执行函数中触发 testFunction,如何才能使其工作?

我发现通过 QuartzGuiceLib 我可以使用一些注释来实现它,通过 Spring 我可以更改配置文件中的某些内容。但是如何在没有任何框架的情况下用纯Java实现它呢?

下面是代码快照:

public class MyJob implements Job {
public MyJob() {
testFunction();

try {
final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
if (!scheduler.checkExists(JOB_KEY)) {
triggerScheduler(scheduler);
} else {
log.info("Job with key {{}} already exist", JOB_KEY);
}
} catch (SchedulerException e) {
log.error("Fail to start scheduler", e);
}
}

public void testFunction() {
}

private void triggerScheduler(final Scheduler scheduler) throws SchedulerException {
final JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withIdentity(JOB_KEY)
.build();

final Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myjob")
.withSchedule(
simpleSchedule()
.withIntervalInSeconds(60)
.repeatForever())
.build();

scheduler.start();

log.info("Scheduling job with key {{}}", jobDetail.getKey());

scheduler.scheduleJob(jobDetail, trigger);
}

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
testFunction();
}
}

最佳答案

将作业和调度程序保留在两个单独的类中可能会更容易,如下所示:

public class MyQuartzScheduler {
public static void main( String[] args ) throws Exception {
JobDetail job = JobBuilder.newJob(MyJob.class)
.withIdentity("dummyJobName", "group1").build();

Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("MyJobTrigger", "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule("0 * * * * ?"))
.build();

Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}

然后是你的工作类别:

public class MyJob implements Job {    
public void testFunction() {
System.out.println("Running Test!");
}

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
testFunction();
}
}

这是改编自 mkyong 教程文章,位于:

https://www.mkyong.com/java/quartz-2-scheduler-tutorial/

对于你的问题的答案,Quartz 确实在每次运行时创建一个新实例: https://stackoverflow.com/a/10463309/1410671

您可以创建您的 Job 类将调用的另一个静态类或工厂,每次调用都会使用相同的实例。

public class MyJob implements Job {

public void testFunction() {
MyClassWithStaticCounter.increaseCounter(1);
System.out.println(MyClassWithStaticCounter.getCounter());
}

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
testFunction();
}
}

你的类有静态的东西:

public class MyClassWithStaticCounter {
private static int counter = 0;

public static void increaseCounter(int i){
counter += i;
}

public static int getCounter(){
return counter;
}
}

关于java - 避免 Quartz 每次都创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51900411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com