问题
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