Java 如何手动停止/中断石英调度程序作业

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18467320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:52:20  来源:igfitidea点击:

how to stop/interrupt quartz scheduler job manually

javaquartz-scheduler

提问by MAS

I am running a simple quartz job in main class which runs every 30 secs.

我在主类中运行一个简单的石英作业,每 30 秒运行一次。

public class Start {
 public static void main(String[] args) throws Exception {    
      SchedulerFactory sf = new StdSchedulerFactory();
      Scheduler sched = sf.getScheduler();
       JobDetail job = newJob(MyJob.class).withIdentity("myJob","XXX").build();
   Trigger trigger = TriggerBuilder.newTrigger()
         .withSchedule(
             SimpleScheduleBuilder.simpleSchedule()
                 .withIntervalInSeconds(30)
             .repeatForever())
                               .build();
    sched.scheduleJob(job, trigger);
     sched.start();
  } 
}

Here i am implementing InterruptableJob like

在这里,我正在实施 InterruptableJob 之类的

 public class MyJob implements InterruptableJob {

private volatile boolean isJobInterrupted = false;

private JobKey jobKey = null;

private volatile Thread thisThread;

public MyJob() {
}

@Override
public void interrupt() throws UnableToInterruptJobException {
    // TODO Auto-generated method stub
    System.err.println("calling interrupt:"+thisThread+"==>"+jobKey);
    isJobInterrupted = true;
    if (thisThread != null) {
        // this call causes the ClosedByInterruptException to happen
        thisThread.interrupt();
    }

}

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    // TODO Auto-generated method stub
    thisThread = Thread.currentThread();

    jobKey = context.getJobDetail().getKey();

    System.err.println("calling execute:"+thisThread+"==>"+jobKey);
}
}

Now i tried to stop the job using another main class like in every possible way with no luck

现在我试图以各种可能的方式使用另一个主类来停止工作,但没有运气

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

     SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();

        // get a "nice round" time a few seconds in the future...
        Date startTime = nextGivenSecondDate(null, 1);

        JobDetail job = newJob(MyJob.class).withIdentity("myJob", "XXX").build();

        Trigger trigger = TriggerBuilder.newTrigger()
        .withSchedule(
                 SimpleScheduleBuilder.simpleSchedule()
                     .withIntervalInSeconds(30)
                 .repeatForever())
                                   .build();

        sched.scheduleJob(job, trigger);

        sched.start();


            try {
                  // if you want to see the job to finish successfully, sleep for about 40 seconds
                Thread.sleep(60000) ;
                  // tell the scheduler to interrupt our job
                  sched.interrupt(job.getKey());
                  Thread.sleep(3 * 1000L);
                } catch (Exception e) {
                  e.printStackTrace();
                }
                System.err.println("------- Shutting Down --------");

                TriggerKey tk=TriggerKey.triggerKey("myJob","group1");
                System.err.println("tk"+tk+":"+job.getKey());
                sched.unscheduleJob(tk);
                sched.interrupt(job.getKey());
                sched.interrupt("myJob");
                sched.deleteJob(job.getKey());
                sched.shutdown();
                System.err.println("------- Shutting Down ");

                sched.shutdown(false);

                System.err.println("------- Shutdown Complete ");

            System.err.println("------- Shutdown Complete ");

    }
}

Can anyone please tell me the correct way to stop the job? Thanks a lot.

谁能告诉我停止工作的正确方法?非常感谢。

回答by Alex

This questionseems to answer the exact problem you're describing:

这个问题似乎回答了您所描述的确切问题:

You need to write a your job as an implementation of InterruptableJob. To interrupt this job, you need handle to Scheduler, and call interrupt(jobKey<<job name & job group>>)

您需要将作业编写为 InterruptableJob 的实现。要中断这项工作,您需要处理Scheduler,并调用interrupt(jobKey<<job name & job group>>)

As-per the InterruptableJobdocumentation:

根据InterruptableJob文档

The interface to be implemented by Jobs that provide a mechanism for having their execution interrupted. It is NOT a requirement for jobs to implement this interface - in fact, for most people, none of their jobs will.

Interrupting a Job is very analogousin concept and challenge to normal interruption of a Thread in Java.

The means of actually interrupting the Job must be implemented within the Job itself (the interrupt() method of this interface is simply a means for the scheduler to inform the Job that a request has been made for it to be interrupted). The mechanism that your jobs use to interrupt themselves might vary between implementations. However the principle idea in any implementation should be to have the body of the job's execute(..) periodically check some flag to see if an interruption has been requested, and if the flag is set, somehow abort the performance of the rest of the job's work.

由提供中断执行机制的作业实现的接口。实现这个接口并不是工作的必要条件——事实上,对于大多数人来说,他们的工作都不会。

中断作业在概念和挑战上与 Java 中线程的正常中断非常相似

实际中断Job 的方法必须在Job 内部实现(这个接口的interrupt() 方法只是调度程序通知Job 已发出中断请求的方法)。您的作业用于中断自身的机制可能因实现而异。然而,任何实现中的主要思想应该是让作业的 execute(..) 的主体定期检查某个标志以查看是否已请求中断,如果设置了标志,则以某种方式中止其余部分的执行工作的工作。

Emphasis mine. It is analogousbut not the same. You're not expected to use Threads (but indeed you could if that's what your Jobdoes...).

强调我的。它是类似的,但不一样。您不应该使用线程(但确实可以,如果这是您Job所做的......)。

An example of interrupting a job can be found in the java source for the class org.quartz.examples.DumbInterruptableJob. It is legal to use some combination of wait() and notify() synchronization within interrupt() and execute(..) in order to have the interrupt() method block until the execute(..) signals that it has noticed the set flag.

可以在类 org.quartz.examples.DumbInterruptableJob 的 java 源代码中找到中断作业的示例。在interrupt() 和execute(..) 中使用wait() 和notify() 同步的某种组合是合法的,以便使interrupt() 方法阻塞,直到execute(..) 发出信号表明它已经注意到集合旗帜。

So I recommend reading the documentationand inspecting examples in the full download.

因此,我建议阅读完整下载中的文档并检查示例。