quartz 2.2.3 自带示例源码解读example6~example10

example6 任务的异常处理

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BadJob1 implements Job {

	private static Logger _log = LoggerFactory.getLogger(BadJob1.class);
	private int calculation;

	public BadJob1() {
	}

	// 此任务会抛出异常
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		JobKey jobKey = context.getJobDetail().getKey();
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();

		int denominator = dataMap.getInt("denominator");
		_log.info("---" + jobKey + " executing at " + new Date()
				+ " with denominator " + denominator);

		// 此任务因为除以0所以抛出异常,只有第1次才会抛出书异常
		try {
			calculation = 4815 / denominator;
		} catch (Exception e) {
			_log.info("--- Error in job!");
			JobExecutionException e2 = new JobExecutionException(e);

			// 放job的map中放入分母,所以下次不会抛出异常
			dataMap.put("denominator", "1");

			// 抛出异常时直接再次触发任务
			e2.setRefireImmediately(true);  
			throw e2;
		}

		_log.info("---" + jobKey + " completed at " + new Date());
	}
}


@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BadJob2 implements Job {

    private static Logger _log = LoggerFactory.getLogger(BadJob2.class);
    private int calculation;

    public BadJob2() {
    }

    // 此任务会抛出异常
    public void execute(JobExecutionContext context)
        throws JobExecutionException {
        JobKey jobKey = context.getJobDetail().getKey();
        _log.info("---" + jobKey + " executing at " + new Date());

     // 此任务因为除以0所以抛出异常
        try {
            int zero = 0;
            calculation = 4815 / zero;
        } catch (Exception e) {
            _log.info("--- Error in job!");
            JobExecutionException e2 = 
                new JobExecutionException(e);
            // quartz将会取消此任务上的触发器,所以此任务不会再执行
            e2.setUnscheduleAllTriggers(true);
            throw e2;
        }

        _log.info("---" + jobKey + " completed at " + new Date());
    }

}


public class JobExceptionExample {

	public void run() throws Exception {
		Logger log = LoggerFactory.getLogger(JobExceptionExample.class);

		log.info("------- Initializing ----------------------");
		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler sched = sf.getScheduler();
		log.info("------- Initialization Complete ------------");
		log.info("------- Scheduling Jobs -------------------");

		// 开始时间秒数为15的位数
		Date startTime = nextGivenSecondDate(null, 15);

		// badJob1 will run every 10 seconds
		// this job will throw an exception and refire
		// immediately
		// job1每10秒运行一次,由于抛出异常,所以会立即再次触发
		JobDetail job = newJob(BadJob1.class).withIdentity("badJob1", "group1")
				.usingJobData("denominator", "0").build();
		SimpleTrigger trigger = newTrigger()
				.withIdentity("trigger1", "group1")
				.startAt(startTime)
				.withSchedule(
						simpleSchedule().withIntervalInSeconds(10)
								.repeatForever()).build();
		Date ft = sched.scheduleJob(job, trigger);
		log.info(job.getKey() + " will run at: " + ft + " and repeat: "
				+ trigger.getRepeatCount() + " times, every "
				+ trigger.getRepeatInterval() / 1000 + " seconds");

		// job2每5秒执行一次,此任务抛出异常后不会再次执行了
		job = newJob(BadJob2.class).withIdentity("badJob2", "group1").build();
		trigger = newTrigger()
				.withIdentity("trigger2", "group1")
				.startAt(startTime)
				.withSchedule(
						simpleSchedule().withIntervalInSeconds(5)
								.repeatForever()).build();
		ft = sched.scheduleJob(job, trigger);
		log.info(job.getKey() + " will run at: " + ft + " and repeat: "
				+ trigger.getRepeatCount() + " times, every "
				+ trigger.getRepeatInterval() / 1000 + " seconds");

		log.info("------- Starting Scheduler ----------------");
		sched.start();
		log.info("------- Started Scheduler -----------------");

		try {
			Thread.sleep(30L * 1000L);
		} catch (Exception e) {
		}

		log.info("------- Shutting Down ---------------------");
		sched.shutdown(false);
		log.info("------- Shutdown Complete -----------------");

		SchedulerMetaData metaData = sched.getMetaData();
		log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
	}

	public static void main(String[] args) throws Exception {

		JobExceptionExample example = new JobExceptionExample();
		example.run();
	}

}


example7 中断任务

public class DumbInterruptableJob implements InterruptableJob {

	private static Logger _log = LoggerFactory
			.getLogger(DumbInterruptableJob.class);

	private boolean _interrupted = false;

	private JobKey _jobKey = null;

	public DumbInterruptableJob() {
	}

	public void execute(JobExecutionContext context)
			throws JobExecutionException {

		_jobKey = context.getJobDetail().getKey();
		_log.info("---- " + _jobKey + " executing at " + new Date());

		try {
			// 通过睡眠模拟任务所花费的时间
			for (int i = 0; i < 4; i++) {
				try {
					Thread.sleep(1000L);
				} catch (Exception ignore) {
					ignore.printStackTrace();
				}

				// 检查任务是否被中断
				if (_interrupted) {
					_log.info("--- " + _jobKey
							+ "  -- Interrupted... bailing out!");
					// 对于特殊的场景我们可以选择抛出一个JobExecutionException异常
					return;
				}
			}

		} finally {
			_log.info("---- " + _jobKey + " completed at " + new Date());
		}
	}

	// 中断任务时的回调函数
	public void interrupt() throws UnableToInterruptJobException {
		_log.info("---" + _jobKey + "  -- INTERRUPTING --");
		_interrupted = true;
	}

}


public class InterruptExample {

	public void run() throws Exception {
		final Logger log = LoggerFactory.getLogger(InterruptExample.class);

		log.info("------- Initializing ----------------------");
		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler sched = sf.getScheduler();
		log.info("------- Initialization Complete -----------");
		log.info("------- Scheduling Jobs -------------------");

		// 开始时间秒数为15的倍数
		Date startTime = nextGivenSecondDate(null, 15);

		// 每5秒执行一次
		JobDetail job = newJob(DumbInterruptableJob.class).withIdentity(
				"interruptableJob1", "group1").build();
		SimpleTrigger trigger = newTrigger()
				.withIdentity("trigger1", "group1")
				.startAt(startTime)
				.withSchedule(
						simpleSchedule().withIntervalInSeconds(5)
								.repeatForever()).build();
		Date ft = sched.scheduleJob(job, trigger);
		log.info(job.getKey() + " will run at: " + ft + " and repeat: "
				+ trigger.getRepeatCount() + " times, every "
				+ trigger.getRepeatInterval() / 1000 + " seconds");

		sched.start();
		log.info("------- Started Scheduler -----------------");

		log.info("------- Starting loop to interrupt job every 7 seconds ----------");
		for (int i = 0; i < 50; i++) {
			try {
				Thread.sleep(7000L);
				sched.interrupt(job.getKey()); // 中断任务
			} catch (Exception e) {
			}
		}

		log.info("------- Shutting Down ---------------------");

		sched.shutdown(true);

		log.info("------- Shutdown Complete -----------------");
		SchedulerMetaData metaData = sched.getMetaData();
		log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");

	}

	public static void main(String[] args) throws Exception {

		InterruptExample example = new InterruptExample();
		example.run();
	}

}

Example 8 Calendar使用

使用Calendar可以排除指定日期,由于没有测试通过,所以就不粘贴这部分示例代码了

Example9 任务监听器

public class SimpleJob1 implements Job {

	private static Logger _log = LoggerFactory.getLogger(SimpleJob1.class);

	public SimpleJob1() {
	}

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		JobKey jobKey = context.getJobDetail().getKey();
		_log.info("SimpleJob1 says: " + jobKey + " executing at " + new Date());
	}

}


public class SimpleJob2 implements Job {

	private static Logger _log = LoggerFactory.getLogger(SimpleJob2.class);

	public SimpleJob2() {
	}

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		JobKey jobKey = context.getJobDetail().getKey();
		_log.info("SimpleJob2 says: " + jobKey + " executing at " + new Date());
	}

}


public class Job1Listener implements JobListener {

  private static Logger _log = LoggerFactory.getLogger(Job1Listener.class);

  public String getName() {
    return "job1_to_job2";
  }

  public void jobToBeExecuted(JobExecutionContext inContext) {
    _log.info("Job1Listener says: Job Is about to be executed.");
  }

  public void jobExecutionVetoed(JobExecutionContext inContext) {
    _log.info("Job1Listener says: Job Execution was vetoed.");
  }

  public void jobWasExecuted(JobExecutionContext inContext, JobExecutionException inException) {
    _log.info("Job1Listener says: Job was executed.");

    // Simple job #2
    JobDetail job2 = newJob(SimpleJob2.class).withIdentity("job2").build();
    Trigger trigger = newTrigger().withIdentity("job2Trigger").startNow().build();

    try {
      inContext.getScheduler().scheduleJob(job2, trigger);
    } catch (SchedulerException e) {
      _log.warn("Unable to schedule job2!");
      e.printStackTrace();
    }

  }

}


public class ListenerExample {

  public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(ListenerExample.class);

    log.info("------- Initializing ----------------------");
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();
    log.info("------- Initialization Complete -----------");
    log.info("------- Scheduling Jobs -------------------");

    JobDetail job = newJob(SimpleJob1.class).withIdentity("job1").build();
    Trigger trigger = newTrigger().withIdentity("trigger1").startNow().build();

    // 设置监听器
    JobListener listener = new Job1Listener();
    Matcher<JobKey> matcher = KeyMatcher.keyEquals(job.getKey());
    sched.getListenerManager().addJobListener(listener, matcher);

    sched.scheduleJob(job, trigger);

    log.info("------- Starting Scheduler ----------------");
    sched.start();
    log.info("------- Waiting 30 seconds... --------------");
    try {
      Thread.sleep(30L * 1000L);
    } catch (Exception e) {
    }

    log.info("------- Shutting Down ---------------------");
    sched.shutdown(true);
    log.info("------- Shutdown Complete -----------------");

    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");

  }

  public static void main(String[] args) throws Exception {

    ListenerExample example = new ListenerExample();
    example.run();
  }

}

Example10 使用插件

从xml中读取任务配置并运行任务,由于实际中没用到,。。。



猜你喜欢

转载自blog.csdn.net/zhuce0001/article/details/53304354