Configuring Quartz.Net to stop a job from executing, if it is taking longer than specified time span

北战南征 提交于 2019-12-19 22:01:53

问题


I am working on making a scheduler, just like Windows Scheduler using Quartz.Net.

In Windows Scheduler, there is an option to stop a task from running if it takes more than the specified time. I have to implement the same in my scheduler.

But I am not able to find any extension method/setting to configure Trigger or Job accordingly.

I request some inputs or suggestions for it.


回答1:


You can write small code to set a custom timout running on another thread. Implement IInterruptableJob interface and make a call to its Interrupt() method from that thread when the job should be interrupted. You can modify the following sample code as per your need. Please make necessary checks/config inputs wherever required.

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.
            }
        }
    }


来源:https://stackoverflow.com/questions/24446215/configuring-quartz-net-to-stop-a-job-from-executing-if-it-is-taking-longer-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!