Search code examples
.net-corequartz

Running simple quartz example in Net Core console app


I'm trying to run simple Quartz 3.x example in .NET Core console app. I have this code (taken from here):

public static async Task Main(string[] args)
{
    // construct a scheduler factory
    NameValueCollection props = new NameValueCollection
    {
        { "quartz.serializer.type", "binary" }
    };
    StdSchedulerFactory factory = new StdSchedulerFactory(props);

    // get a scheduler
    IScheduler sched = await factory.GetScheduler();
    await sched.Start();

    // define the job and tie it to our HelloJob class
    IJobDetail job = JobBuilder.Create<HelloJob>()
        .WithIdentity("myJob", "group1")
        .Build();

    // Trigger the job to run now, and then every 40 seconds
    ITrigger trigger = TriggerBuilder.Create()
        .WithIdentity("myTrigger", "group1")
        .StartNow()
        .WithSimpleSchedule(x => x
            .WithIntervalInSeconds(40)
            .RepeatForever())
    .Build();

    await sched.ScheduleJob(job, trigger);
}

public class HelloJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        await Console.Out.WriteLineAsync("HelloJob is executing.");
    }
}

With the changes to 3.x everything becoming async it never executes HelloJob. It just runs to end and exits the console app. Am I missing something here? Can we not run quartz jobs like this in core console app?

I can run the old version in regular console app in 2.x version (without async methods) just fine:

public static void Main(string[] args)
{
    // construct a scheduler factory
    ISchedulerFactory schedFact = new StdSchedulerFactory();

    // get a scheduler
    IScheduler sched = schedFact.GetScheduler();
    sched.Start();

    // define the job and tie it to our HelloJob class
    IJobDetail job = JobBuilder.Create<HelloJob>()
        .WithIdentity("myJob", "group1")
        .Build();

    // Trigger the job to run now, and then every 40 seconds
    ITrigger trigger = TriggerBuilder.Create()
      .WithIdentity("myTrigger", "group1")
      .StartNow()
      .WithSimpleSchedule(x => x
          .WithIntervalInSeconds(40)
          .RepeatForever())
      .Build();

    sched.ScheduleJob(job, trigger);
}

public class HelloJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        Console.WriteLine("HelloJob is executing.");
    }
}

Solution

  • I didn't use Quartz 2.x in the console apps, but behaviour for the version 3.x is kind of expected: after sched was scheduled an application continues its execution and exits.

    Probably it's not the most elegant solution but these two lines at the end should help:

    ...
    sched.ScheduleJob(job, trigger);
    Console.ReadKey()
    await sched.Shutdown();