你能顺序运行两个不同的Quartz作业实例吗?

时间:2017-03-01 16:17:06

标签: java quartz

嗨我有一个工作1触发了非常小的一分钟,并且工作2每5分钟触发一次。因此,每隔五分钟我们就会同时运行这些工作,我想避免这种情况,并迫使第二份工作开始等待另一份工作完成。我见过@DisallowConcurrentExecution但这只会避免并行运行相同作业的两个实例而不是不同作业之间的运行。

1 个答案:

答案 0 :(得分:0)

对于那些感兴趣的人,我设法做的是将两个工作融合在一个工作中,但有两个不同的触发器指向同一个工作。每个触发器都有自己的触发时间,现在每个触发器的数据映射中都存在参数,而不是作业数据映射。失火政策也改为MisfireHandlingInstructionFireAndProceed

这是代码:

public class QuartzTest {

    public static final String PROCESS_TRIGGER_MAP_KEY = "process";

    public static void main( String[] args ) throws SchedulerException, InterruptedException {
    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 ) ).withMisfireHandlingInstructionFireAndProceed() ).build();
    trigger1.getJobDataMap().put( PROCESS_TRIGGER_MAP_KEY, new MessagePrinter() {

        @Override
        public void print() {
        System.out.println( new Timestamp( System.currentTimeMillis() ) + " This is process 1" );
        }
    } );
    scheduler.scheduleJob( job1, trigger1 );

    CronTrigger trigger2 = newTrigger().withIdentity( "trigger2", "group1" ).forJob( job1 ).startAt( new Date() ).withSchedule( cronSchedule( getCronExpression( 2 ) ).withMisfireHandlingInstructionFireAndProceed() ).build();
    trigger2.getJobDataMap().put( PROCESS_TRIGGER_MAP_KEY, new MessagePrinter() {

        @Override
        public void print() {
        System.out.println( new Timestamp( System.currentTimeMillis() ) + " This is process 2" );
        }
    } );
    scheduler.scheduleJob( trigger2 );

    Thread.sleep( 5 * 60 * 1000 );
    }

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

    }

}

这是工作类

@DisallowConcurrentExecution
public class TestJob implements Job {

    @Override
    public void execute( JobExecutionContext context ) throws JobExecutionException {
    MessagePrinter mp = (MessagePrinter) context.getTrigger().getJobDataMap().get( QuartzTest.PROCESS_TRIGGER_MAP_KEY );
    if ( mp != null ) {
        mp.print();
    } else {
        System.out.println( new Timestamp( System.currentTimeMillis() ) + " Job started" );
    }
    System.out.println( new Timestamp( System.currentTimeMillis() ) + " Job sleeping 10s..." );
    try {
        Thread.sleep( 10 * 1000 );
    } catch ( InterruptedException e ) {
        e.printStackTrace();
    }
    System.out.println( new Timestamp( System.currentTimeMillis() ) + " Job finished." );
    }

}

处理器类:

public abstract class MessagePrinter {
    public MessagePrinter() {

    }

    public abstract void print();

}