嗨我在石英中有两个作业实例,我想不要并行运行,我简化了下面例子中的代码,以显示不符合我期望的内容。
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.
那为什么不发生这种情况呢?
答案 0 :(得分:0)
来自docs:
@DisallowConcurrentExecution:
一个注释,它将Job类标记为一个不能同时执行多个实例的注释(其中实例基于JobDetail定义 - 或者换句话说基于JobKey)。
JobKey由名称和组
组成在您的示例中,名称不相同,因此这是两个不同的作业。
DisallowConcurrentExecution确保在触发另一个job1#thread2之前完成job1#thread1。