简体   繁体   中英

Quartz: triggering multiple jobs

In Quarts, can I use a single trigger to schedule multiple jobs, so that all the jobs gets executed in parallel. What is the best way to do this.

Example, every hour execute Jobs j1, j2, ..., jn in parallel. Assuming that there is no dependency between the jobs.

You can't associate multiple jobs with the same trigger (a given job can have multiple triggers, but not vice versa), but you can set up multiple identical triggers, one for each job.

In order to get them running in parallel, you need to ensure that Quartz's thread pool has enough capacity to do so. See here for the config options for the thread pool.

You can build a trigger job that triggers the other jobs. Make it configurable by using the JobMap properties, and you can reuse the class for triggering an arbitrary set of jobs (and maybe executing the first for yourself).

I ended up making a help function GetTrigger

class Program
{
    static void Main(string[] args)
    {
        Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter { Level = Common.Logging.LogLevel.Info };            

        IJobDetail jobOne = JobBuilder.Create<JobOne>()
            .WithIdentity(typeof(JobOne).Name)
            .Build();

        IJobDetail jobTwo = JobBuilder.Create<JobTwo>()
            .WithIdentity(typeof(JobTwo).Name)
            .Build();

        var jobOneTrigger = GetTrigger(new TimeSpan(0, 0, 5), jobOne);
        var jobTwoTrigger = GetTrigger(new TimeSpan(0, 0, 5), jobTwo);

        IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        scheduler.ScheduleJob(jobOne, jobOneTrigger);
        scheduler.ScheduleJob(jobTwo, jobTwoTrigger);

        scheduler.Start();
    }

    private static ITrigger GetTrigger(TimeSpan executionTimeSpan, IJobDetail forJob)
    {            
        return TriggerBuilder.Create()
            .WithIdentity(forJob.JobType.Name+"Trigger")
            .StartNow()
            .WithSimpleSchedule(x => x
                .WithInterval(executionTimeSpan)
                .RepeatForever())  
            .ForJob(forJob.JobType.Name)
            .Build();
    }
}

public class JobOne : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        Console.WriteLine("JobOne");
    }
}

public class JobTwo : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        Console.WriteLine("JobTwo");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM