嗨,我有两个不希望并行运行的石英作业实例,我在下面的示例中简化了代码,以显示不符合我期望的代码。

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#thread2之前已完成job1#thread1。

09-10 21:35