如何中断或停止当前运行的石英作业?

我有一些在Java Quartz Jobs的帮助下执行的任务,但我需要在我的代码中通过某些条件来停止某些任务。 我读到这可以通过InterruptableJob完成。 但我不明白我该怎么做呢?

你需要写一份你的工作作为InterruptableJob的实现。 要中断此作业,您需要处理Scheduler ,并调用interrupt(jobKey<>)

请看看@ javadoc上面的类,石英发行版也包含一个例子(example7)。

在使用Spring的Quartz 2.1中,您可以:

 @Autowired private Scheduler schedulerFactoryBean; //injected by spring ... ... List currentlyExecuting = schedulerFactoryBean.getCurrentlyExecutingJobs(); //verifying if job is running for (JobExecutionContext jobExecutionContext : currentlyExecuting) { if(jobExecutionContext.getJobDetail().getKey().getName().equals("JobKeyNameToInterrupt")){ result = schedulerFactoryBean.interrupt(jobExecutionContext.getJobDetail().getKey()); } } 

我认为最好的解决方案是本主题中描述的解决方案: http : //forums.terracotta.org/forums/posts/list/7700.page

我刚刚将stop stop标志设置为true后引入了“sleep”,以使作业干净利落。

  @Override public void interrupt() throws UnableToInterruptJobException { stopFlag.set(true); try { Thread.sleep(30000); } catch (InterruptedException e) { //logger.error("interrupt()", e); } Thread thread = runningThread.getAndSet(null); if (thread != null) thread.interrupt(); } 

我不知道为什么没有人提到这一点,或者在问到这个问题时可能没有这个。

Scheduler实例有一个名为shutdown的方法。

  SchedulerFactory factory = new StdSchedulerFactor(); Scheduler scheduler = factory.getScheduler(); 

以上用于开始像这样的工作

  scheduler.start(); 

使用标志或其他东西知道何时停止作业运行。 然后用

  scheduler.shutdown(); 

我是如何实现我的要求的:

 if(flag==true) { scheduler.start(); scheduler.scheduleJob(jobDetail, simpleTrigger); } else if(flag==false) { scheduler.shutdown(); } 

其中jobDetail和simpleTrigger是自解释的。

希望能帮助到你。 🙂