unscheduling job in quartz - c#

I am using Quartz to schedule job in my c# .net application. I am storing all data in database. My code is :
ISchedulerFactory schedFact = new StdSchedulerFactory(properties);
_scheduler = schedFact.GetScheduler();
_scheduler.Start();
job = JobBuilder.Create<JobTask>()
.WithIdentity("job1", "group1")
.Build();
trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.WithSchedule(
CronScheduleBuilder.CronSchedule("0 0/5 * * * ?"))
.Build();
_scheduler.ScheduleJob(job, trigger);
Now I would like to give user function so user can disable(unschedule) job. I have look in quartz tutorial but I can't find the way to do it in c#.

You can call following method in IScheduler
//
// Summary:
// Remove the indicated Quartz.Trigger from the scheduler.
bool UnscheduleJob(string triggerName, string groupName);

Your Job class can implement IInterruptableJob interface and implement
public void Interrupt()
{
JobKey jobKey = new JobKey(JobName, MyService.GroupName);
Scheduler.Interrupt(jobKey);
}

Related

Quartz Scheduler block inactive user job

I am currently working with Quartz Scheduler and I am trying to make a feature, which will be blocking an user if he is inactive for example for more than two days, but unfortunately I didn't work with Quartz Scheduler and I have no idea how to do that.
Well then, you will have a daily cron or an hourly cron (depending on the sensitivity) that checks that value and update the user.
public class CheckForInactiveUsers: IJob
{
public async Task Execute(IJobExecutionContext context)
{
// here you do your business
}
}
IJobDetail job = JobBuilder.Create<CheckForInactiveUsers>()
.WithIdentity("checkForInactiveUsers", "group1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(1)
.RepeatForever())
.Build();
await scheduler.ScheduleJob(job, trigger);

Quartz.net Scheduler Trigger 4 times with difference of some miliseconds Deployed at IIS

I Just Want To Trigger Event Only once in a Day At specific Time But it trigger 4 Times with difference of some miliseconds
Below Is My Scheduler Class
public class CustomerEventAssigningJobScheduler
{
private static IScheduler _scheduler;
public static IScheduler scheduler
{
get
{
if (_scheduler == null)
{
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;
_scheduler = scheduler;
}
return _scheduler;
}
}
public static async Task Start()
{
await scheduler.Start();
IJobDetail job = JobBuilder.Create<CustomerEventAssigningJob>().WithIdentity("CustomerEventAssigningJob").Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("CustomerEventAssigningJob")
.WithDailyTimeIntervalSchedule
(s =>
s.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(00, 10))
.WithIntervalInHours(24)
.InTimeZone(TimeZoneInfo.Utc)
)
.Build();
await scheduler.ScheduleJob(job, trigger);
}
}
I have Tried: .EndingDailyAfterCount(1)
But after adding it does not trigger
screen shot of log is here:
Please check below, as we do not need to use OnEveryDay(), as we already used WithIntervalInHours(24).
ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInHours(24)
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(00, 10))
)
.Build();
Its need to check server configuration/deployment, because on local machine, its ran one time.

Define list of triggers to execute job

I would like to execute same job in different scheduled times.
Here is one sample which I wrote:
ISchedulerFactory schedFact = new StdSchedulerFactory();
var setoftrigs = new HashSet<ITrigger>();
for (int x=0; x<=2; x++)
{
setoftrigs.Add(TriggerBuilder.Create().WithIdentity("trigger" + x.ToString(), "group1").WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(21, 44+x)).Build());
}
// get a scheduler
IScheduler sched = schedFact.GetScheduler().GetAwaiter().GetResult();
sched.Start();
// create job
IJobDetail job = JobBuilder.Create<RunJob>()
.WithIdentity("job1", "group1")
.Build();
sched.ScheduleJob(job, setoftrigs, false);
The problem is that in certain time jobs is not executed.
But if I do on this way:
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(21, 49))
.Build();
sched.ScheduleJob(job, trigger);
...it works fine.
What I want to achieve is to have a list of triggers when job should be executed.
How to do that?

Show next job execution scheduled time

I was wondering if Quartz.Net has a way to tell (or better write in the logs) on the next execution... I mean, I have got a job that runs at 10:00 AM and it's scheduled to run every two hours... is there a way I can write something as Next run on 12:00AM? or do I have to parse the cron expression, then add it to the current date?
Thanks in advance
Not sure what logger you are using, but this approach should work with any logger that you can create instances of. Create instance of logger and pass it to job via JobDataMap and then use it inside of job. IJobExecutionContext.NextFireTimeUtc will tell you next execution time which you can write to a logger
using System;
using System.Threading.Tasks;
using NLog;
using Quartz;
using Quartz.Impl;
namespace QuartzSampleApp
{
public class Program
{
private static async Task Main(string[] args)
{
var logger = LogManager.GetCurrentClassLogger();
StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = await factory.GetScheduler();
await scheduler.Start();
IJobDetail job = JobBuilder.Create<HelloJob>()
.WithIdentity("job1", "group1")
.Build();
job.JobDataMap["logger"] = logger; // add logger to job data map
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(10)
.RepeatForever())
.Build();
await scheduler.ScheduleJob(job, trigger);
await Task.Delay(TimeSpan.FromSeconds(60));
await scheduler.Shutdown();
Console.WriteLine("Press any key to close the application");
Console.ReadKey();
}
// simple log provider to get something to the console
}
public class HelloJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync("Greetings from HelloJob!");
var logger = context.JobDetail.JobDataMap["logger"] as ILogger;
logger.Log(LogLevel.Info, "Next job execution at " + context.NextFireTimeUtc);
}
}
}

Scheduling Cron Jobs With Quartz.NET

I'm trying to schedule some jobs using Quartz.NET but I cannot get it working. I tried the following code but nothing happened when the specified time was met.
public void Test()
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IScheduler scheduler = schedulerFactory.GetScheduler();
IJobDetail jobDetail = JobBuilder.Create<SatellitePaymentGenerationJob>()
.WithIdentity("TestJob")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.ForJob(jobDetail)
.WithCronSchedule("0 26 18 * * ?")
.WithIdentity("TestTrigger")
.StartNow()
.Build();
scheduler.ScheduleJob(jobDetail, trigger);
scheduler.Start();
}
UPDATE:
I also tried the following just to make sure it's not the Cron expression that is causing the problem. Did not work for me either...
IJobDetail jobDetail = JobBuilder.Create<SatellitePaymentGenerationJob>()
.WithIdentity("TestJob", "TestGroup")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.ForJob(jobDetail)
.WithSimpleSchedule(x=> x.RepeatForever().WithIntervalInSeconds(10).WithMisfireHandlingInstructionFireNow())
.StartAt(new DateTimeOffset(DateTime.UtcNow.AddSeconds(10)))
.WithIdentity("TestTrigger", "TestGroup")
.Build();
scheduler.ScheduleJob(jobDetail, trigger);
scheduler.Start();
Console.WriteLine(DateTime.UtcNow.ToLongTimeString());
Console.WriteLine(trigger.GetNextFireTimeUtc());
Note that trigger.GetNextFireTimeUtc() returns a valid time value, but the job never gets triggered.
Where did I go wrong?
Everything is ok with your sample code, maybe the Execute method from SatellitePaymentGenerationJob implementation is wrong, or the job is executed but not in the expected time. In the current shape it will be fired at 18:26 every day, is that what you want?
Compare with my code (working):
class Program
{
static void Main(string[] args)
{
Test();
}
public static void Test()
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IScheduler scheduler = schedulerFactory.GetScheduler();
IJobDetail jobDetail = JobBuilder.Create<SatellitePaymentGenerationJob>()
.WithIdentity("TestJob")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.ForJob(jobDetail)
.WithCronSchedule("0 45 20 * * ?")
.WithIdentity("TestTrigger")
.StartNow()
.Build();
scheduler.ScheduleJob(jobDetail, trigger);
scheduler.Start();
}
}
internal class SatellitePaymentGenerationJob : IJob
{
public void Execute(IJobExecutionContext context)
{
Console.WriteLine("test");
}
}

Categories