Search code examples
c#quartz.net.net-standard-2.0quartz.net-3.0

Manually triggering a job not working


Using Quartz.Net I want to manually trigger a job without a schedule (for now). However the job runs on startup (which I don't want), then fails to respond to a manual trigger (main problem).

private IScheduler _scheduler;

public void SetupAndTestScheduler()
{
    ISchedulerFactory sf = new StdSchedulerFactory();
    _scheduler = sf.GetScheduler().Result;
    _scheduler.Start();
    _scheduler.ScheduleJob(
        new JobDetailImpl(nameof(TestDataJob), typeof(TestDataJob)), null);

    // manually trigger the job
    _scheduler.TriggerJob(jobKey: new JobKey(nameof(TestDataJob)));
}

public class TestDataJob : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        // blah blah blah
    }
}

I'm on NetStandard2.0, with Quartz.Net Alpha 3. I'm wondering whether this is a problem with version 3?


Solution

  • In Quartz.Net 3.x Alpha, methods like scheduler.Start, scheduler.ScheduleJob, etc..., are now async, which means you need to await them. What happens in your code is that the Task returned by ScheduleJob is not even executed before the call to Shutdown, as you are not awaiting it.

    You can follow the Quick Start Guide to see exactly how to use it.

    In a nutshell, what you need to do:

    • use the async/await semantics
    • add the job to the scheduler by calling the scheduler.AddJob method (your job must be declared as durable in that case, as you are not associating a trigger with it)
    • and then you can call the scheduler.TriggerJob() method to trigger your job