Search code examples
c#quartz

Lambda expression to replace if statement


I would like to remove the if statement with a lambda expression to avoid duplication

if (string.IsNullOrEmpty(ConfigurationSettings.Hour.ToString()))
{
       service.ScheduleQuartzJob(q =>
       q.WithJob(() =>
       JobBuilder.Create<ServiceJob>().Build())
       .AddTrigger(() => TriggerBuilder.Create()
       .WithCronSchedule(ConfigurationSettings.RunAtSchedule)
       .Build()));
}
else
{
       service.ScheduleQuartzJob(q =>
       q.WithJob(() =>
       JobBuilder.Create<ServiceJob>().Build())
       .AddTrigger(() => TriggerBuilder.Create()
       .WithSchedule(CronScheduleBuilder
       .DailyAtHourAndMinute(ConfigurationSettings.Hour,
       ConfigurationSettings.RunAtMinute))
       .Build()));
}

How can I refactor this to replace the if statement using a lambda?

Many thanks

Garry


Solution

  • It's unclear what you mean by replacing it with a lambda. But I think this may be close to what you are after:

    var builder = TriggerBuilder.Create();
    var schedule = string.IsNullOrEmpty(ConfigurationSettings.Hour.ToString()) 
        ? builder.WithCronSchedule(ConfigurationSettings.RunAtSchedule)
        : builder.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(ConfigurationSettings.Hour, ConfigurationSettings.RunAtMinute));
    
    service.ScheduleQuartzJob(
      q => q.WithJob(
        () => JobBuilder.Create<ServiceJob>().Build())
                        .AddTrigger(() => schedule.Build())
      ) 
    );
    

    I'm not familiar with Quartz, but I assume the above should work. If you need to pass it all within the lambda, you could do this instead:

    service.ScheduleQuartzJob(
      q => q.WithJob(
        () => JobBuilder.Create<ServiceJob>().Build())
                        .AddTrigger(
                              () => (string.IsNullOrEmpty(ConfigurationSettings.Hour.ToString()) 
                                  ? TriggerBuilder.Create().WithCronSchedule(ConfigurationSettings.RunAtSchedule)
                                  : TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(ConfigurationSettings.Hour, ConfigurationSettings.RunAtMinute))
                                ).Build()
                 )
          ) 
    );
    

    Note: I think I matched all the closing parenthesis, but it's possible I missed one as I typed this on mobile.