Search code examples
schedulingquartz.netatlas

Quartz.net daily jobs keeps getting executed every minute


I have the code below. I would expect it to run daily at 17:00 if the config setting was not set otherwise the config setting will be used. So far no issue, the variable is set correctly. However: Instead of daily the job gets executed every minute and I cant figure out why. Is the scheduler not set up correctly?

        TimeSpan timeOfExecution;

        if (!TimeSpan.TryParse(ConfigurationManager.AppSettings["TimeOfExecution"], out timeOfExecution))
        {
            timeOfExecution = new TimeSpan(17, 0, 0);

        }

       var job = JobBuilder.Create<DailyReportJob>()
            .WithIdentity("DailyReportJob")
            .Build();

        var trigger = TriggerBuilder.Create()
            .WithIdentity("DailyReportTrigger")
            .WithDailyTimeIntervalSchedule(s => s.OnEveryDay().StartingDailyAt(new TimeOfDay(timeOfExecution.Hours, timeOfExecution.Minutes)))
            .Build();

        Scheduler.ScheduleJob(job, trigger);
        Scheduler.ListenerManager.AddJobListener(AutofacJobListener);
        Scheduler.Start();

Solution

  • The default time for this trigger is every minute, since you haven't specified otherwise.

    You can check all the intervals using this code:

    var dt = trigger.GetNextFireTimeUtc();
    
    for (int i = 0; i < 10; i++)
    {
        if (dt == null)
            break;
    
        Console.WriteLine(dt.Value.ToLocalTime());
        dt = trigger.GetFireTimeAfter(dt);
    }
    

    If you want to schedule your job to run once a day at 5pm, you can change your code adding a 24 hour interval:

    var trigger = TriggerBuilder.Create()
        .WithIdentity("DailyReportTrigger")
        .WithDailyTimeIntervalSchedule(s => s.OnEveryDay().StartingDailyAt(new TimeOfDay(timeOfExecution.Hours, timeOfExecution.Minutes)))
        .WithIntervalInHours(24)
        .Build();