c#Quartz如何切换安排一项旨在每小时和每天运行的工作

时间:2016-07-14 09:25:52

标签: c#-4.0 quartz-scheduler quartz.net

我是Quartz.Net的新手。我的工作计划每小时和每天运行。请在下面找到我的日程服务详情。

现在我想切换时间表,以便我可以启用或禁用每小时或每日时间表。

public class SchedulerService : ISchedulerService
{
    private readonly IScheduler _scheduler;
    private readonly IConfigurationReader _configReader;

    public SchedulerService(IScheduler scheduler, IConfigurationReader configReader)
    {
        _scheduler = scheduler;
        _configReader = configReader;
    }       
    public void Start()
    {
        StartScheduledJobs();
    }   
    public void Stop()
    {
        _scheduler.Shutdown(true);
    }       
    private void StartScheduledJobs()
    {
        try
        {
            _scheduler.Start();

            if(_configReader.HourlyChangeJobEnabled) //Will this work? or is this the way to achieve this?
                ScheduleHourlyChangesJob();
            if(_configReader.DailyChangeJobEnabled) 
                ScheduleDailyChangesJob();
        }
        catch (Exception ex)
        {
            _logProvider.Error("", ex);
        }
    }   

    private void ScheduleHourlyChangesJob()
    {
        var jobDetail = JobBuilder.Create<SimpleJob>()
            .WithIdentity("hourlyJob", "group1")
            .UsingJobData("mode","hourly")
            .Build();

        var trigger = TriggerBuilder.Create()
            .WithIdentity("hourlyTrigger", "group1")
            .WithSchedule(CronScheduleBuilder.CronSchedule("0 0 1/1 ? * *")
            .Build();

        _scheduler.ScheduleJob(jobDetail, trigger);
    }

    private void ScheduleDailyChangesJob()
    {
        var jobDetail = JobBuilder.Create<SimpleJob>()
            .WithIdentity("dailyJob", "group1")
            .UsingJobData("mode", "daily")
            .Build();

        var trigger = TriggerBuilder.Create()
            .WithIdentity("dailyTrigger", "group1")
            .WithSchedule(CronScheduleBuilder.CronSchedule("0 0 0 1/1 * ?"))
            .Build();

        _scheduler.ScheduleJob(jobDetail, trigger);
    }
}

任何人都可以帮我解决这个问题吗?

由于

1 个答案:

答案 0 :(得分:1)

看起来您的代码将启用新触发器,但不会删除旧触发器。以下代码是关于更改从http://www.quartz-scheduler.org/documentation/quartz-2.x/cookbook/UpdateTrigger.html

获取的触发器的示例
// retrieve the trigger
Trigger oldTrigger = sched.getTrigger(triggerKey("oldTrigger", "group1");

// obtain a builder that would produce the trigger
TriggerBuilder tb = oldTrigger.getTriggerBuilder();

// update the schedule associated with the builder, and build the new trigger
// (other builder methods could be called, to change the trigger in any desired way)
Trigger newTrigger = tb.withSchedule(simpleSchedule()
    .withIntervalInSeconds(10)
    .withRepeatCount(10)
    .build();

sched.rescheduleJob(oldTrigger.getKey(), newTrigger);