开发者

Quartz: triggering multiple jobs

开发者 https://www.devze.com 2022-12-29 20:00 出处:网络
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.

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, 开发者_如何学JAVA..., 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");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消