I have what should be a simple task. I create a new job, make if durable and add add using the IScheduler.AddJob method. The job is registered but for the life of me I can not figure how to assign triggers to it.
This is from the tutorial:
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
IScheduler sched = schedFact.GetScheduler();
sched.Start();
// construct job info
JobDetail jobDetail = new JobDetail("myJob", null, typeof(DumbJob));
// fire every hour
Trigger trigger = TriggerUtils.MakeHourlyTrigger();
// start on the next even hour
trigger.StartTime = TriggerUtils.GetEvenHourDate(DateTime.UtcNow);
trigger.Name = "myTrigger";
sched.ScheduleJob(jobDetail, trigger);
Related
I'm trying to perform the following code on a console application that uses Quarz.NET, but I got the following exception.
Here's the snippet of code
public Task AddSchedule(FlussoAnagraficaItem item)
{
if(this.scheduler == null) throw new Exception("scheduler is null, has the InitAsync method been invoked?");
var jobItemType = this.jobCreatorFactory.CreateJobFromAnagraficaFlussiItem(item);
// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create(jobItemType)
.WithIdentity(item.Description, "sender")
.Build();
// Trigger the job to run now, and then repeat every 10 seconds
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity($"trigger_{item.Description}", "sender")
.StartNow().WithCronSchedule(item.Timespan)
.Build();
// Tell quartz to schedule the job using our trigger
return this.scheduler.ScheduleJob(job, trigger);
}
Where item.Timespan is "00 16 * * 5" , what's wrong?
Thanks
I need to persist a counter value between executions of a Grails Quartz plugin job. This runs at the correctly timed intervals and I can set the jobDataMap and read the value back correctly (during the same execution run), but it refuses to remember it between between executions.
I've set concurrent = false as the docs advised. Any ideas? I just need to persist and increment a counter. I want to avoid using a DB if at all possible, I think this should just use memory? Or other work arounds?
My TestJob.groovy, in /server/grails-app/jobs:
package myPackage
class MyJob {
static triggers = {
simple repeatInterval: 5000l // execute job every 5 seconds
}
def concurrent = false // Don't run multiple simultaneous instances of this job
def execute(context) {
if(context.jobDetail.jobDataMap['recCounter'] == null) { context.jobDetail.jobDataMap['recCounter'] = 1 }
else { context.jobDetail.jobDataMap['recCounter'] = context.jobDetail.jobDataMap['recCounter'] + 1 }
println(context.jobDetail.jobDataMap['recCounter'])
}
The output when run is a new line with '1' every 5 seconds. It should be incrementing the counter each time.
1
1
1
1
etc..
I'm running Grails 3.3.9 and build.gradle has compile "org.grails.plugins:grails-spring-websocket:2.4.1" in dependencies
Thanks
I have never used context object in my apps, but a counter can be implemented in a straight-forward way:
class MyJob {
//some static stuff
AtomicInteger counter = new AtomicInteger()
def execute(context) {
counter.incrementAndGet()
println counter.intValue()
}
}
I have a cron job which has multiple triggers all triggers have been scheduled for the interval of lets say 5 min, now I need to update job data map at runtime, for that I need that particular trigger which requires to update but I am failing to get that particular trigger, I am doing something like that
String cronExpression = "0 0/5 * * * ?"
String triggername = "mytrigger" + System.currentTimeMillis()
JobDataMap jobDataMap = new JobDataMap([host: config.host, port: config.port, username: config.username, password: config.password])
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(triggername)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).usingJobData(jobDataMap)
.build()
MyJob.schedule(trigger)
Any idea how can I get that particular trigger which I have to update?
Try something like that:
List<Trigger> triggers = quartzScheduler.jobGroupNames.collect {
quartzScheduler.getJobKeys(GroupMatcher.groupEquals(it)).collect {
quartzScheduler.getTriggersOfJob(it)
}
}.flatten()
It will return all your scheduled triggers. After get them you can do what you need in JobDataMap.
I suggest use a familiar trigger identity, it make easier to find a specific one at runtime.
I saved the trigger name in database, and when I need to update that trigger I simply fetch that trigger like this:
TriggerKey triggerKey = new TriggerKey(triggerName_from_db);
try {
Trigger trigger = quartzScheduler.getTrigger(triggerKey)
if (trigger?.key?.name) {
trigger.jobDataMap['host'] = config.host
trigger.jobDataMap['port'] = config.port
trigger.jobDataMap['username'] = config.username
trigger.jobDataMap['password'] = config.password
}
quartzScheduler.rescheduleJob(triggerKey, trigger)
}catch (SchedulerException ex) {
log.error ex.toString()
}
i have a job with one trigger, actually my problem is similar to this Quartz Java resuming a job excecutes it many times
Here is my code when i was trying to turn on/off job. The problem is when i was trying to reschedule job after paused for long time(in my case is one day), the trigger executes too many in the same time when i reschedule the job. And how i use class PauseAwareCronTrigger in my code ? {PauseAwareCronTrigger is class solution from Quartz Java resuming a job excecutes it many times
}
def rescheduleJob(config) {
def triggerName = "com.divusi.sipfo."+getJobKeyName(config.namaNotifikasi)
def triggerName1 = getJobKeyName(config.namaNotifikasi)
//def triggers = quartzScheduler.getTriggersOfJob(new JobKey("pisReminder", "job"))
//def trigger = quartzScheduler.getTrigger(triggerKey("pisReminder", "job"))
def trigger = quartzScheduler.getTrigger(new TriggerKey(getJobKeyName(config.namaNotifikasi), "job"))
//def trigger = quartzScheduler.getTrigger(new TriggerKey("kpRealizationList", "job"))
//Trigger trigger = triggers[0];
/*quartzScheduler.rescheduleJob(trigger.getKey(), TriggerBuilder.newTrigger()
.withIdentity(triggerName,"job")
.withSchedule(CronScheduleBuilder.cronSchedule("0 0/1 * * * ?"))
.build()) */
if(config.notifikasiAktif) {
quartzScheduler.rescheduleJob(trigger.getKey(), TriggerBuilder.newTrigger()
.withIdentity(getJobKeyName(config.namaNotifikasi),"job")
.withSchedule(CronScheduleBuilder.cronSchedule("0/1 * * * * ?"))
.build())
}else{
quartzScheduler.pauseTrigger(trigger.getKey())
}
/*trigger.cronExpression = "0/1 * * * * ?" config.cronExpression
quartzScheduler.rescheduleJob(new TriggerKey("pisReminder", "job"), trigger) */
}
I Am trying to use Quartz.Net so as to Schedule Jobs Within a Windows Service that I developped.
I included the following code on the Onstart Method, scheduler is a Class attribute
private readonly IScheduler scheduler;
logger = LogManager.GetLogger(typeof (TelegestionService));
scheduler = new StdSchedulerFactory().GetScheduler();
var job = new JobDetail("job1", "group1", typeof (HelloJob));
var trigger = new SimpleTrigger("trigger1", "group1", runTime);
scheduler.ScheduleJob(job, trigger);
This works fine for me. I got the Job running.
Now I'am trying to make the scheduler embedded remotely accessible, based en Example12 in the Quartz source Examples (the Console Server/Client works fine).
var properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteServer";
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
properties["quartz.scheduler.exporter.port"] = "555";
properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
properties["quartz.scheduler.exporter.channelType"] = "tcp";
scheduler = new StdSchedulerFactory(properties).GetScheduler();
The service starts correctly and so does the scheduler but i cannot remotely schedule the Job using a Console/Winform Client (Connection refused).
I checked the LISTENING ports on my server using SysInternals TcpView and I cannot find the 555 port specified above.
Am suspecting an issue related to .Net Remoting but cannot figure out how to resolve this.
Any ideas ?
Thanks in advance.
could use http://topshelf-project.com/ to host Scheduler which will provide hostFactory and using that could shelf host via HttpSelfHostServer, http is better as you could invoke job via controller. sample code as below
hope this helps.
using System;
using System.Configuration;
using System.Web.Http;
using System.Web.Http.SelfHost;
using Topshelf;
class Program
{
static void Main(string[] args)
{
HostFactory.Run(hostConfigurator =>
{
if (!Uri.TryCreate("http://localhost:8080", UriKind.RelativeOrAbsolute, out var hostname))
{
throw new ConfigurationErrorsException($"Could not uri");
}
var serviceName = "my service";
var hostConfiguration = new HttpSelfHostConfiguration(hostname);
hostConfiguration.Routes.MapHttpRoute("API", "{controller}/{action}/{id}", (object)new
{
id = RouteParameter.Optional
});
var httpSelfHostServer = new HttpSelfHostServer(hostConfiguration);
// Impl.Scheduler would be your implementation of scheduler
hostConfigurator.Service<Impl.Scheduler>(s =>
{
s.ConstructUsing(name => new Impl.Scheduler());
s.WhenStarted(tc =>
{
tc.Start();
httpSelfHostServer.OpenAsync().Wait();
});
s.WhenStopped(tc =>
{
tc.Stop();
//dispose scheduler implementation if using IOC container
httpSelfHostServer.CloseAsync().Wait();
});
});
hostConfigurator.RunAsLocalSystem();
hostConfigurator.SetDescription(serviceName);
hostConfigurator.SetDisplayName(serviceName);
hostConfigurator.SetServiceName(serviceName);
});
}
}