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?
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();
}
}
}
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With