-2

Can anyone help me a create an email schedular that sends emails every 15 min using quartz in asp.net core?

Sid_Sh
  • 9
  • This question is a bit broad. What have you tried so far? – bsod_ Jun 06 '22 at 09:36
  • 1
    This is a useful link when trying to get up and running with Quartz.net - https://andrewlock.net/using-quartz-net-with-asp-net-core-and-worker-services/ – bsod_ Jun 06 '22 at 09:37
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Jun 06 '22 at 10:48

1 Answers1

1

I found this blog useful when implementing a simple scheduler using quartz.

You can use cronmaker.com to generate the cron expressions you require.

The following string will schedule a job every 15 minutes "0 0/15 * 1/1 * ? *".

To implement the Quartz scheduler first add Quartz to your Program Class.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddQuartz(q =>  
            {
                q.UseMicrosoftDependencyInjectionJobFactory();

                // Create a "key" for the job
                var jobKey = new JobKey("EmailJob");

                // Register the job with the DI container
                q.AddJob<EmailJob>(opts => opts.WithIdentity(jobKey));
                
                // Create a trigger for the job
                q.AddTrigger(opts => opts
                    .ForJob(jobKey) // link to the EmailJob
                    .WithIdentity("EmailJob-trigger") // give the trigger a unique name
                    .WithCronSchedule("0 0/15 * 1/1 * ? *")); // run every 15 Minutes

            });
            services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);

        });
}

Next you will need to create a job class which implements IJob from the Quartz library.

[DisallowConcurrentExecution] //Add this so jobs are not scheduled more than once at a time
public class EmailJob : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        //TODO:: Add email implementation Here
        return Task.CompletedTask;
    }
}

You can use the blog I mentioned above to allow you to easier register jobs and put your cron job configuration inside your config file.

One note on the blog is to not use "MicrosoftDependencyInjectionScopedJobFactory" and rather use "UseMicrosoftDependencyInjectionJobFactory" as all jobs in Quartz are now scoped.

Kobus
  • 31
  • 2
  • 5