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

随声附和 提交于 2019-12-01 21:08:39

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