Ajay Srikanth
Ajay Srikanth

Reputation: 1185

Cron Expression not working correctly

I've .net windows service which schedules Quartz jobs, I've the following code to start my job at 4 AM every day and repeat every 12 hours. Start time below will be different for each job. The problem here is it is not starting at 4 AM when I say, but it is only running at 12 AM and 12 PM every day. How can I ensure that it starts exactly at the time that I asked it to StartAtTime? If I reduce the value in my cron expression to either 1/2 and change the start time to some 2 PM or 3 PM whatever, it works as expected.

var startAtTime = DateTime.Today.AddHours(localTime[Key]);

if (startAtTime.ToUniversalTime() < DateTime.UtcNow)
{
    startAtTime = startAtTime.AddDays(1);
}

ITrigger objESLJobTrigger = TriggerBuilder.Create()
                           .WithIdentity("ESLTrigger-",             AuditType.ESL.ToString())
                           .StartAt(new DateTimeOffset(startAtTime))
                           .WithCronSchedule("0 0 0/12 ? * SUN-SAT", x => x.WithMisfireHandlingInstructionIgnoreMisfires())
                           .Build();

Upvotes: 0

Views: 2428

Answers (1)

Set
Set

Reputation: 49769

It works as should. See

  • .StartAt() method defines when start the trigger, not job.
  • and your cron expression 0 0 0/12 ? * SUN-SAT means exactly "run job at at 12 AM and 12 PM every day" (you may use cronmaker to check).

Cron Scheduler is not helpful in your case, as it works with intervals in different way that you expect:

/ - used to specify increments. For example, “0/15” in the seconds field means “the seconds 0, 15, 30, and 45”. And “5/15” in the seconds field means “the seconds 5, 20, 35, and 50”. You can also specify ‘/’ after the ‘’ character - in this case ‘’ is equivalent to having ‘0’ before the ‘/’. ‘1/3’ in the day-of-month field means “fire every 3 days starting on the first day of the month”.

So expression like 0 0 4/12 ? * SUN-SAT will run every 12 hours at 4AM and 4PM. And 0 0 5/12 ? * SUN-SAT will run every 12 hours at 5AM and 5PM. And StartAt() method only define when first job will be triggered (at 4AM or 4PM), it does not do offset for cron expression.

Just use SimpleSchedule instead:

ITrigger objESLJobTrigger = TriggerBuilder.Create()
                           .WithIdentity("ESLTrigger-", AuditType.ESL.ToString())
                           .StartAt(new DateTimeOffset(startAtTime))
                           .WithSimpleSchedule(x => x
                               .WithIntervalInHours(12)
                               .RepeatForever())
                           .Build();

Upvotes: 1

Related Questions