使用Quartz.NET安排Cron作业

时间:2013-02-16 16:31:15

标签: c# quartz-scheduler jobs quartz.net quartz.net-2.0

我正在尝试使用Quartz.NET安排一些工作,但我无法让它工作。我尝试了以下代码,但在达到指定时间时没有发生任何事情。

    public void Test()
    {
        ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
        IScheduler scheduler = schedulerFactory.GetScheduler();

        IJobDetail jobDetail = JobBuilder.Create<SatellitePaymentGenerationJob>()
            .WithIdentity("TestJob")
            .Build();
        ITrigger trigger = TriggerBuilder.Create()
            .ForJob(jobDetail)
            .WithCronSchedule("0 26 18 * * ?")
            .WithIdentity("TestTrigger")
            .StartNow()
            .Build();
        scheduler.ScheduleJob(jobDetail, trigger);
        scheduler.Start();
    }

更新

我还尝试了以下方法,以确保它不是引起问题的Cron表达式。对我来说也不起作用......

IJobDetail jobDetail = JobBuilder.Create<SatellitePaymentGenerationJob>()
                .WithIdentity("TestJob", "TestGroup")
                .Build();
            ITrigger trigger = TriggerBuilder.Create()  
                .ForJob(jobDetail)
                .WithSimpleSchedule(x=> x.RepeatForever().WithIntervalInSeconds(10).WithMisfireHandlingInstructionFireNow())
                .StartAt(new DateTimeOffset(DateTime.UtcNow.AddSeconds(10)))
                .WithIdentity("TestTrigger", "TestGroup")
                .Build();
            scheduler.ScheduleJob(jobDetail, trigger);
            scheduler.Start();
            Console.WriteLine(DateTime.UtcNow.ToLongTimeString());
            Console.WriteLine(trigger.GetNextFireTimeUtc());

请注意,trigger.GetNextFireTimeUtc()会返回有效的时间值,但作业永远不会被触发。

我哪里出错了?

1 个答案:

答案 0 :(得分:7)

您的示例代码一切正常,也许SatellitePaymentGenerationJob实现中的Execute方法错误,或者作业已执行但未在预期时间内执行。在目前的形状,它将在每天18:26被解雇,这是你想要的吗?

与我的代码(工作)比较:

class Program
{
    static void Main(string[] args)
    {
        Test();
    }

    public static void Test()
    {
        ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
        IScheduler scheduler = schedulerFactory.GetScheduler();

        IJobDetail jobDetail = JobBuilder.Create<SatellitePaymentGenerationJob>()
            .WithIdentity("TestJob")
            .Build();
        ITrigger trigger = TriggerBuilder.Create()
            .ForJob(jobDetail)
            .WithCronSchedule("0 45 20 * * ?")
            .WithIdentity("TestTrigger")
            .StartNow()
            .Build();
        scheduler.ScheduleJob(jobDetail, trigger);
        scheduler.Start();
    }
}

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