Cron作业调度程序每天都要添加新的石英作业?

时间:2015-08-04 08:59:04

标签: c# quartz-scheduler quartz.net

我想每天凌晨1点运行crobjob来添加新的Quartz.net作业,这些作业将在同一天运行一次并被删除。

到目前为止,我可以添加工作来收听每场足球比赛,但不知道如何添加一个cron工作来每天添加这些工作。

class LiveScheduledJobs : IScheduledJob
    {
     public IScheduler Run()
        {
            var schd = GetScheduler();
            if (!schd.IsStarted)
                schd.Start();
            string jobName = "", triggerName = "";
            using (var db = new ABCDataContext())
            {
                var fixtures = db.Fixtures;
                string group = "livematch";                
                foreach (var item in fixtures.Where(blahblah))
                {
                    jobName = "match" + item.Id;
                    triggerName = "trigger" + item.Id;                   
                    int categoryId = db.Fixture_Category_Mappings.FirstOrDefault(f => f.FixtureId == item.Id).CategoryId;
                    var seasonStage = db.Season_Stage_Mappings.FirstOrDefault(f => f.Id == item.SeasonStageId);
                    // Define the Job to be scheduled
                    var job = JobBuilder.Create<LiveMatchJob>()
                        .WithIdentity(jobName, group )
                        .UsingJobData("url", item.AutoUrl)
                        .UsingJobData("seasonId", seasonStage.SeasonId)
                        .UsingJobData("categoryId", categoryId)
                        .UsingJobData("stageId", seasonStage.StageId)
                        .RequestRecovery()
                        .Build();

                    DateTimeOffset startTime = new DateTime(item.Time.Year, item.Time.Month, item.Time.Day,
                                              item.Time.Hour, item.Time.Minute, item.Time.Second);


                    ITrigger triggerLive = TriggerBuilder.Create()
                    .WithIdentity(triggerName, group)
                    .StartAt(startTime)
                    .WithSimpleSchedule(x =>x.WithIntervalInMinutes(2).RepeatForever())
                    .Build();

                    // Validate that the job doesn't already exists
                    if (schd.CheckExists(new JobKey(jobName, group)))
                    {
                        schd.DeleteJob(new JobKey(jobName, group));
                    }
                    var schedule = schd.ScheduleJob(job, triggerLive);
                }
            }
            return schd;

        }

LiveMatchJob:

  public class LiveMatchJob : IJob
{
    private Object thisLock = new Object();
    public void Execute(IJobExecutionContext context)
    {
        JobKey jobKey = context.JobDetail.Key;
        var triggerKey = context.Trigger.Key;
        JobDataMap dataMap = context.JobDetail.JobDataMap;
        string url = dataMap.GetString("url");
        int seasonId = dataMap.GetInt("seasonId");
        int categoryId = dataMap.GetInt("categoryId");
        int stageId = dataMap.GetInt("stageId");

        using (var db = new ABCDataContext())
        {
            try
            {

                var fixture = db.Fixtures.FirstOrDefault(f => f.AutoUrl == url.Trim());
                if (fixture.IsComplete)
                {                        
                    context.Scheduler.DeleteJob(jobKey);  >> remove job when done
                }
                else
                {

                    context.Scheduler.PauseTrigger(triggerKey);
                    ....
                    context.Scheduler.ResumeTrigger(triggerKey);
                }
            }
            catch (Exception ex)
            {
                ....
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我添加了另一个调度程序:

class CronJobScheduler : IScheduledJob
{
    public IScheduler Run()
    {
        var schd = GetScheduler();
        if (!schd.IsStarted)
            schd.Start();


        var trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("cronjobTrigger", "cronGroup1")
                       .WithCronSchedule("0 0 1 1/1 * ? *")
                      .StartAt(DateTime.UtcNow)
                       .WithPriority(1)
                     .Build();


        var job = JobBuilder.Create<CronJob>()
                    .WithIdentity("cronjob", "cronGroup1")
                    .RequestRecovery()
                    .Build();

        var schedule = schd.ScheduleJob(job, trigger);
        return schd;

    }




    // Get an instance of the Quartz.Net scheduler
    private static IScheduler GetScheduler()
    {
        try
        {
            var properties = new NameValueCollection();
            properties["quartz.scheduler.instanceName"] = "ServerScheduler";

            // set remoting expoter
            properties["quartz.scheduler.proxy"] = "true";
            properties["quartz.scheduler.proxy.address"] = string.Format("tcp://{0}:{1}/{2}", "localhost", "555",
                                                                         "QuartzScheduler");

            // Get a reference to the scheduler
            var sf = new StdSchedulerFactory();//properties);
            return sf.GetScheduler();

        }
        catch (Exception ex)
        {
            Console.WriteLine("Scheduler not available: '{0}'", ex.Message);
            throw;
        }
    }
    public void Shutdown(IScheduler schd)
    {
        schd.Shutdown();
    }
}

从Cronjob,我打电话给其他调度程序

 public class CronJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        var sj = new LiveScheduledJobs();
        var schd = sj.Run();
    }
}

答案 1 :(得分:0)

您不需要添加额外的计划程序。创建一个计划其他作业的作业。

例如,创建一个继承自IJob的JobSchedulingJob:

public class JobScheduling : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        var schd = context.Scheduler;
        scheduleOtherJobs(scheduler);//this is where you schedule the other jobs    
    }
}

然后,使用CronTrigger安排此JobSchedulingJob每天运行。