gpt4 book ai didi

java - Quartz @DisallowConcurrentExecution 不工作

转载 作者:太空宇宙 更新时间:2023-11-04 11:43:56 24 4
gpt4 key购买 nike

您好,我有两个 quartz 作业实例,我不想并行运行,我简化了下面示例中的代码以显示哪些内容不符合我的预期。

public class QuartzTest {

public static void main( String[] args ) throws SchedulerException {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.start();

JobDetail job1 = newJob( TestJob.class ).withIdentity( "job1", "group1" ).build();
CronTrigger trigger1 = newTrigger().withIdentity( "trigger1", "group1" ).startAt( new Date() ).withSchedule( cronSchedule( getCronExpression( 1 ) ) ).build();
scheduler.scheduleJob( job1, trigger1 );

JobDetail job2 = newJob( TestJob.class ).withIdentity( "job2", "group1" ).build();
CronTrigger trigger2 = newTrigger().withIdentity( "trigger2", "group1" ).startAt( new Date() ).withSchedule( cronSchedule( getCronExpression( 1 ) ) ).build();
scheduler.scheduleJob( job2, trigger2 );

for ( int i = 0; i < 5; i++ ) {
System.out.println( trigger1.getNextFireTime() );
System.out.println( trigger2.getNextFireTime() );
try {
Thread.sleep( 1 * 60 * 1000 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}

private static String getCronExpression( int interval ) {
return "0 */" + interval + " * * * ?";

}

}

这是工作类别

@DisallowConcurrentExecution
public class TestJob implements Job {

@Override
public void execute( JobExecutionContext context ) throws JobExecutionException {
System.out.println( "Job started" );
System.out.println( "Job sleeping 30s..." );
try {
Thread.sleep( 30 * 1000 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
System.out.println( "Job finished." );
}

}

因此,我在这里安排两个作业每分钟运行一次(在实际情况下,一个作业每分钟运行一次,另一个作业每 5 运行一次),这是我得到的输出:

Job started
Job sleeping 30s...
Job started
Job sleeping 30s...
Job finished.
Job finished.

所以两个作业都是并行运行的,因为 job1 在运行之前等待 job2 完成的顺序序列会给我这个序列

Job started
Job sleeping 30s...
Job finished.
Job started
Job sleeping 30s...
Job finished.

那么为什么这没有发生呢?

最佳答案

来自文档:

@DisallowConcurrentExecution:

一种注释,将 Job 类标记为不得同时执行多个实例(其中实例基于 JobDetail 定义 - 或者换句话说基于 JobKey)。

JobKey由名称和组组成

在您的示例中,名称不同,因此这是两个不同的作业。

DisallowConcurrentExecution 确保 job1#thread1 在触发另一个 job1#thread2 之前完成。

关于java - Quartz @DisallowConcurrentExecution 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520618/

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