Question3r
Question3r

Reputation: 3752

How to start a scheduled job using Quartz.Net?

I created a .Net 5 worker service application and installed the Quartz.AspNetCore package.

I want to run code based on a cron expression, e.g. every 5 minutes. I created a class MyJob implementing Ijob and register it during DI setup

    public static void Main(string[] args)
    {
        Host
            .CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services
                    .AddQuartz(quartzConfiguration =>
                    {
                        quartzConfiguration.ScheduleJob<MyJob>(jobConfiguration =>
                        {
                            jobConfiguration.WithCronSchedule("20/20 0 0 ? * * *"); // Every 20 seconds starting at second 20
                        });
                    })
                    .AddQuartzHostedService(quartzConfiguration => // I think this code is useful ?
                    {
                        quartzConfiguration.WaitForJobsToComplete = true;
                    })
                    .AddHostedService<Worker>();
            })
            .Build()
            .Run();
    }

But the job itself never executes. When calling quartzConfiguration.AddJob<MyJob>() doesn't give me access to the method .WithCronSchedule().

So how can I tell Quartz to register a job and execute it based on a cron expression?

Upvotes: 1

Views: 1673

Answers (1)

Rowan Freeman
Rowan Freeman

Reputation: 16348

The cron expression 20/20 0 0 ? * * * means "every 20 seconds, after the first 20 seconds, on the first minute of the first hour.

So basically, 00:00:20 and 00:00:40, or 20 seconds past midnight and 40 seconds past midnight.

Check to see if this is the cron you intended. Everything else looks correct.

Upvotes: 1

Related Questions