How to make a Job raise an EventHandler in Quartz.Net?

感情迁移 提交于 2020-01-15 06:13:27

问题


I have a Console Application that instantiates a Quartz Scheduler.
I would like a Job to raise an event Handler so that the "Mother App" calls a particular Method.
The problem is that the Job Class seems to be pretty isolated to the external classes apparently.
I am sure there is a good way to do this but I did not stumble upon it yet.

public class RestartJob : IJob
{        
    public RestartJob()
    {
    }

    public virtual void Execute(IJobExecutionContext context)
    {
        //Send Restart EventHandler Subscription to Console.            
    }
}

回答1:


I solved my problem by implementing a singleton on the class containing the Scheduler Logic. Works a charm. Hope this could help other to solve what seems to me as a "Must-Have" feature.

public class Skeduler
{
    private static Skeduler instance;

    public static Skeduler Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Skeduler();
            }
            return instance;
        }
    }

    public delegate void SendRestartX();
    public event SendRestartX SendRestart;

    public void doSendRestart()
    {
        if (SendRestart!=null)
            SendRestart();
    }

    //(Job Methods & Logics Goes Here)

 }

public class RestartJob : IJob
{
    //Required
    public RestartJob()
    {
    }

    public virtual void Execute(IJobExecutionContext context)
    {
        Skeduler.Instance.doSendRestart();
    }

}

Usage :

    public MainClass
    {   
        public void Run()
        {
          skeduler = Skeduler.Instance;
          skeduler.SendRestart += new Skeduler.SendRestartX(MethodToCall);
        }
    }



回答2:


You can pass the event handler within a JobDataMap and then use the event handler from your job.

When Creating your job

IJobDetail job = JobBuilder.Create<RestartJob>().WithIdentity("job"), "group")
        .SetJobData(new JobDataMap{{"event-handler", YourEventHandler}});

On your job class:

public class RestartJob : IJob
{        
    public RestartJob()
    {
    }

    public virtual void Execute(IJobExecutionContext context)
    {
        var @event = context.JobDetail.JobData["event-handler"];
        @event?.Invoke(YourEventParameters); 
    }
}



回答3:


You can try this : Create IJobDetail :

IJobDetail job = JobBuilder.Create<LogJob>().WithIdentity("job"), "group")
        .UsingJobData("id", 123).Build();
job.JobDataMap["SOMENAME"] = this;

Usage :

public void Execute(IJobExecutionContext context) {
    JobDataMap dataMap = context.JobDetail.JobDataMap;
    CLASSNAME SOMENAME = dataMap["SOMENAME"] as MediaPlaylistsAds;
    int id = (int)dataMap["id"];
    SOMENAME.SOMEFUNC(id);
}


来源:https://stackoverflow.com/questions/8828722/how-to-make-a-job-raise-an-eventhandler-in-quartz-net

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