配置Quartz.Net以停止执行作业,如果它花费的时间超过指定的时间跨度

Was*_*ari 4 asp.net jobs triggers scheduler quartz.net

我正在制作一个调度程序,就像使用Quartz.Net的Windows Scheduler一样.

在Windows计划程序中,如果任务花费的时间超过指定时间,则可以选择停止运行任务.我必须在我的调度程序中实现相同的功能.

但我无法找到任何扩展方法/设置来相应地配置触发器或作业.

我请求一些意见或建议.

Kaj*_*nha 8

您可以编写小代码来设置在另一个线程上运行的自定义时间.实现IInterruptableJob接口,并在作业中断时从该线程调用其Interrupt()方法.您可以根据需要修改以下示例代码.请在需要时进行必要的检查/配置输入.

public class MyCustomJob : IInterruptableJob
    {
        private Thread runner;
        public void Execute(IJobExecutionContext context)
        {
            int timeOutInMinutes = 20; //Read this from some config or db.
            TimeSpan timeout = TimeSpan.FromMinutes(timeOutInMinutes);
            //Run your job here.
            //As your job needs to be interrupted, let us create a new task for that.
            var task = new Task(() =>
                {
                    Thread.Sleep(timeout);
                    Interrupt();
                });

            task.Start();
            runner = new Thread(PerformScheduledWork);
            runner.Start();
        }

        private void PerformScheduledWork()
        {
            //Do what you wish to do in the schedled task.

        }

        public void Interrupt()
        {
            try
            {
                runner.Abort();
            }
            catch (Exception)
            {
               //log it! 

            }
            finally
            {
                //do what you wish to do as a clean up task.
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)