Search code examples
c#quartz-schedulerquartz.net

Pass information between jobs in Quartz.NET


I have two Quartz.NET jobs that run occasionally which I need to pass information between. How do I do this?

Below is an example class for setting the data:

[PersistJobDataAfterExecution]
[DisallowConcurrentExecution]
public class PushingJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        var keys = context.Scheduler.GetJobKeys(GroupMatcher<JobKey>.AnyGroup());

        foreach (var key in keys)
        {
            var detail = context.Scheduler.GetJobDetail(key);
            if (detail.JobType == typeof(PullingJob))
            {
                detail.JobDataMap.Put("Foo", "Bar");
            }
        }
    }
}

And here is an example for getting the data:

[PersistJobDataAfterExecution]
[DisallowConcurrentExecution]
public class PullingJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        Console.WriteLine("Foo property = " + context.MergedJobDataMap.GetString("Foo"));
    }
}

Solution

  • If you are using a DI engine, you can share a single instance object between those two jobs instance, with a concurrent dictionary in it.

    Otherwise, you can always share a static concurrent dictionary between them even without the DI engine (less elegant, but it works) :)

    For example, with injection:

    [PersistJobDataAfterExecution]
    [DisallowConcurrentExecution]
    public class PushingJob : IJob
    {
         DataObject _data;
    
         // with injection
         public PushingJob(DataObject data)
         {
             _data= data;
         }
    
         public void Execute(IJobExecutionContext context)
         {
            var keys = context.Scheduler.GetJobKeys(GroupMatcher<JobKey>.AnyGroup());
    
            foreach (var key in keys)
            {
                var detail = context.Scheduler.GetJobDetail(key);
                if (detail.JobType == typeof(PullingJob))
                {
                    data.MyDict.AddOrUpdate("Foo", "Bar");
                }
            }
        }
    }
    
    [PersistJobDataAfterExecution]
    [DisallowConcurrentExecution]
    public class PullingJob : IJob
    {
         DataObject _data;
    
         // with injection
         public PushingJob(DataObject data)
         {
             _data= data;
         }
    
         public void Execute(IJobExecutionContext context)
         {
            Console.WriteLine("Foo property = " + _data.MyDict.GetOrAdd("Foo"));
         }
    }