How to create quartz job that will runs every N seconds even if job takes more time

我怕爱的太早我们不能终老 提交于 2019-12-06 10:11:35

问题


What I'm trying to achieve: I have a secondly trigger that fires every 5 secods, and stateful job, that takes sometimes more than 5 seconds (7 for example) and what I have now

start: 00:00:00
end  : 00:00:07
start: 00:00:07 < right after previous has finished

what I want :

start: 00:00:00
it should run at 00:00:05 but it hasn't
end  : 00:00:07 
start: 00:00:10 (5 seconds after previous, successive or not)

I have tried quartz.net version 2 and 1.
Job:

    [PersistJobDataAfterExecution]
    [DisallowConcurrentExecution]
    public class StatefulJob : IJob (or IStatefulJob in 1.x version)
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("StateFull START " + DateTime.Now.ToString());
            Thread.Sleep(7000);
            Console.WriteLine("StateFull END " + DateTime.Now.ToString());
        }
    }

Trigger:

var trigger1 = TriggerBuilder
                .Create()
                .WithSimpleSchedule(x => 
                    x.WithIntervalInSeconds(timeout)
                    .RepeatForever()
                .Build();

EDIT I have tried to use WithMisfireHandlingInstructionIgnoreMisfires(), but missfires happens due to scheduler being shutdown, or because there are no available threads, In my case - jobs does not execute because I use StatefulJob. Maybe I'm wrong, but behavior stays the same.

EDIT2 Ok, solution with 'running' flag works perfect in single threaded app. But if I runs this job in few threads (with different params) it would not work So, is it possible to achieve behavior like I want using quartz ?


回答1:


What if you let your job run concurrently, but amend it to do nothing if the job is already running, eg something like.

public class StatefulJob : IJob 
{
    private static bool Running;

    public void Execute(IJobExecutionContext context)
    {                       
        if (Running)
            return;

        Running = true;                                     
        try
        {
            Console.WriteLine(" StateFull START " + DateTime.Now.ToString());
            Thread.Sleep(7000);
            Console.WriteLine(" StateFull END " + DateTime.Now.ToString());
        }
        finally
        {
            Running = false;
        }

    }            
}


来源:https://stackoverflow.com/questions/16520645/how-to-create-quartz-job-that-will-runs-every-n-seconds-even-if-job-takes-more-t

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