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

前端 未结 1 435
醉梦人生
醉梦人生 2021-01-18 18:05

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 mo

相关标签:
1条回答
  • 2021-01-18 18:53

    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.
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题