Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Quartz.Net Job from lambda?

Tags:

c#

quartz.net

Is it possible to create a job from a lambda in Quartz.net?

I have a lot of tasks I need to run, and I'd really like to avoid having to create dozens of classes one for each job. I don't have any need for any advanced setting, I just need to call a method every now and then.

scheduler.ScheduleJob(() => DoSomething(a), TimeSpan.FromSeconds(10));
scheduler.ScheduleJob(() => DoAnotherThing(b), TimeSpan.FromSeconds(20));
scheduler.ScheduleJob(() => DoThis(c), TimeSpan.FromHours(2));
scheduler.ScheduleJob(() => DoThat(d), TimeSpan.FromMinutes(30));
...

I'd create a extension method for this, but it seems each job requires it's own type to be able to create an IJob, and this makes things harder than they should be.

Any ideas on how to accomplish this?

like image 878
Natan Avatar asked Jan 18 '17 17:01

Natan


2 Answers

Ok, I was missing jobdata for parameters. I was able to accomplish this with the following code, if anyone needs it:

using Quartz;
using System;

namespace MyApp
{
    public static class SchedulerExtensions
    {
        public static DateTimeOffset ScheduleJob(this IScheduler scheduler, Action action, TimeSpan initialDelay, TimeSpan interval)
        {
            var data = new JobDataMap();
            data.Add("_", action);

            var jobDetail = JobBuilder.Create<GenericJob>().UsingJobData(data).Build();

            var trigger = TriggerBuilder.Create()
                .StartAt(DateTimeOffset.UtcNow.Add(initialDelay))
                .WithSimpleSchedule(s => s.WithInterval(interval).RepeatForever())
                .Build();

            return scheduler.ScheduleJob(jobDetail, trigger);
        }

        class GenericJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                (context.JobDetail.JobDataMap["_"] as Action)?.Invoke();
            }
        }
    }
}
like image 68
Natan Avatar answered Nov 11 '22 04:11

Natan


Wrote a little extention library which allows to sue lambda syntax.

scheduler.ScheduleJob(() => Console.WriteLine("With TriggerBuilder"), 
 builder => builder.StartNow()
 .WithSimpleSchedule(x => x
    .WithIntervalInSeconds(10)
    .RepeatForever()));

scheduler.ScheduleJob(() => Console.WriteLine("With int delay and interval"), 0, 10);

Nuget: https://www.nuget.org/packages/Quartz.Lambda/

Github: https://github.com/midianok/Quartz.Lambda/

like image 22
IGusev Avatar answered Nov 11 '22 03:11

IGusev