是否有可能杀死当前正在运行的Quartz Job?

问题描述 投票:11回答:3

我记得我们不能杀死当前正在运行的Quartz Job,但是我们可以中断并在必要时进行布尔检查,无论我们是否需要继续进行后续操作。

即使我们实现InterruptableJob并调用scheduler.interrupt来中断Job,当前执行的作业仍将在服务器中运行。

例如:

  1. 作业通过Hibernate触发了一个命名的SQL查询,这需要很长时间
  2. 已经对第三方服务器进行了呼叫,其中第三方服务器需要很长时间来响应

http://neopatel.blogspot.in/2011/05/quartz-stop-job.html http://forums.terracotta.org/forums/posts/list/3191.page

有人可以纠正我的理解并解释我如何杀死或阻止“当前”执行的工作?

quartz-scheduler
3个回答
3
投票

正如你所说,在JAVA中,没有办法打断“粗暴”的石英工作。

您可以将作业的逻辑封装在单独的Thread中,并使用ExecutorService运行它。

看看这个例子:https://stackoverflow.com/a/2275596/1517816

假设您的QuartzJob是Test类,并在Task类中移动您的业务逻辑。

希望能帮助到你


8
投票

你可以创建一个名为JobBase的新抽象类,例如实现IJob接口并插入抽象方法:public abstract void ExecuteJob(IJobExecutionContext context);

在JobBase上,您可以像这样实现方法Execute

public abstract class JobBase : IJob,IInterruptableJob
{
     private Thread currentThread;
     private ILog logger;
     public JobBase(ILog logger)
     {
        this.logger=logger;
     }
        public void Execute(IJobExecutionContext context)
        {

            var thread = new Thread(()=> 
            {
                try
                {
                    this.ExecuteJob(context);
                }
                catch(Exception ex)
                {
                    this.logger.ErrorFormat("Unhandled exception {0}",ex.ToString());

                }
            });

            thread.Start();
            this.currentThread = thread;
            this.currentThread.Join();  
        }
        public abstract void ExecuteJob(IJobExecutionContext context);

        public void Interrupt()
        {   
            currentThread.Abort();
        }
}

每个Job都将实现JobExecute方法。

  public class TestJob :JobBase
{
    private ILog logger;
    public TeJob(ILog logger):base(logger)
    {
    }

    public override ExecuteJob(IJobExecutionContext context)
    {
    }
}

假设使用一些工厂来创建一个Job

对于停止工作,你将调用方法scheduler.Interrupt(new JobKey(jobName));


1
投票

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

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是自解释的。

希望能帮助到你。 :)

© www.soinside.com 2019 - 2024. All rights reserved.