public class CronTriggerApp {
public static void main(String[] args) {
try {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail job = JobBuilder.newJob(Main.class)
.withIdentity("dummyJobName", "group1").build();
System.out.println(job);
Date startTime = DateBuilder.nextGivenSecondDate(null, 5);
System.out.println(startTime);
// run every 20 seconds infinite loop
CronTrigger crontrigger = TriggerBuilder
.newTrigger()
.withIdentity("TwentySec", "group1")
.startAt(startTime)
.startNow()
.withSchedule(CronScheduleBuilder.cronSchedule("* * * ? * *"))//0 53 12 * * ? *
.build();
scheduler.start();
scheduler.scheduleJob(job, crontrigger);
//scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Main implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Trigger Starts.."+new Date());
System.out.println("ALL_OFF");
}
}
By using above code i can able to schedule cron job..but if want cancel the schedule time how can able to cancel or stop the schedule task?
can any one plz help me how can i stop or cancel the scheduled task?
You can expose an endpoint to interrupt it. And use the following function of scheduler to stop it.
scheduler.interrupt(jobDetail.getKey());
Related
i have a class where i perform some activities, and i want to create a job that will handle this operation automatically, scheduled every x minutes for example.
I am using Quartz, this class implements Job, and in my driver class i'm creating my jobdetail, scheduler and trigger and then starting it. However, the job isn't being executed, log info :
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
The code for the scheduler in my driver class:
try {
JobDetail job = JobBuilder.newJob(TestMkFPMJob.class).withIdentity("TestMkFPMJob").build();
Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(Integer.parseInt(strTimeSched)).repeatForever()).build();
SchedulerFactory schFactory = new StdSchedulerFactory();
Scheduler sch = schFactory.getScheduler();
sch.start();
sch.scheduleJob(job, trigger);
}
catch (SchedulerException e)
{
e.printStackTrace();
System.out.println("Scheduler Error");
}
With "TestMkFPMJob" being the job class where my operations are handled, and strTimeSched is already fetched and set as 120 fetched from
I've been looking for a similar issue but can't seem to find any tip to move forward, appreciate any.
Please note that this is my first time using Quartz/Job scheduling.
The log entry with NOT STARTED is misleading, as it is shown whenever a QuartzScheduler instance is created. It does not mean that the jobs are not running. It is written after the line Scheduler sch = schFactory.getScheduler(); is executed and the scheduler is started in the next line.
If I take your example and run it on my pc, it is working as designed:
public class Quartz {
public static void main(String[] args) {
try {
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("myJob").build();
Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(Integer.parseInt("10")).repeatForever()).build();
SchedulerFactory schFactory = new StdSchedulerFactory();
Scheduler sch = schFactory.getScheduler();
sch.start();
sch.scheduleJob(job, trigger);
}
catch (SchedulerException e)
{
e.printStackTrace();
System.out.println("Scheduler Error");
}
}
public static class MyJob implements Job {
#Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("runnning job");
}
}
}
Using Timer and TimerTask.
Not able to understand why is this configuration starting the task immediately on deployment (using this in a web based Spring app). It should be started at today.getTime and then must repeat every day.
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 3);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
MyTask task = new MyTask();
Timer timerJob = new Timer();
timerJob.schedule(task, today.getTime(),
TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
I think, it would be better to use CronTrigger or Trigger with 24hours repeat interval.
Example of CronTrigger:
public class CronTriggerRunner {
public static void main(String args[]) throws SchedulerException, Exception {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
JobDetail job = JobBuilder.newJob(ClassToRun.class).withIdentity("jobName", "group").build();
// Starting CronTrigger
String exp = "0 0 9 * * ?"; //trigger format, everyday at 9:00 am
Trigger trigger = TriggerBuilder.newTrigger()
.startNow()
.withSchedule(
CronScheduleBuilder.cronSchedule(exp))
.build();
// Planning job detail
scheduler.scheduleJob(job, trigger);
// starting scheduler
scheduler.start();
}
}
ClassToRun.java
public class ClassToRun implements Job {
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try{
//doSomething
}
catch(Exception e){
e.printStackTrace(System.out);
}
}
}
Everyday at 9:00 am, public void execute() function will doSomething :D
Hope this will help. Please let me know.
EDIT: You need to download and add 2 jar files. 1) quartz-2.2.1.jar 2) slf4j-api-1.6.6.jar
I am new to java and trying to learn quartz. I have main method
public static void main(String[] args) throws SchedulerException {
try {
JobDetail job1 = JobBuilder.newJob(Job1.class).withIdentity("job1", "group1").build();
Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("cronTrigger1", "group1")
.withSchedule(CronScheduleBuilder.weeklyOnDayAndHourAndMinute(3, 12, 38)).build();
Scheduler scheduler1 = new StdSchedulerFactory().getScheduler();
scheduler1.start();
scheduler1.scheduleJob(job1, trigger1);
scheduler1.shutdown();
}
catch (Exception e) {
e.printStackTrace();
}
Which works fine. It prints to the console on 3rd day of the week at 12:38 pm.
Now, what I want to do is to reschedule the trigger, so that it deletes the previous stored trigger and creates a new trigger with new schedule.
I read a lot of things at a lot of places but I just can't seem to understand clearly what I actually have to do, for ex:
public void execute(JobExecutionContext context) throws JobExecutionException {
Trigger newTigger = what ever you want;
Trigger oldTrigger = context.getTrigger()
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);
}
and also this:
// Define a new Trigger
Trigger trigger = newTrigger()
.withIdentity("newTrigger", "group1")
.startNow()
.build();
// tell the scheduler to remove the old trigger with the given key, and
// put the new one in its place
sched.rescheduleJob(triggerKey("oldTrigger", "group1"), trigger);
but I can't understand the approach(I do understand what is happening in the code though). Thanks in advance.
The requirements were, to be able to dynamically schedule jobs using Quartz. After looking at examples on the web I found most of the examples were of static scheduling. I want to create quartz job within a loop. Currently only one job is running. Please help me. My code is given below
while (iterator.hasNext()) {
JSONObject obj =iterator.next();
ISocialMediaPoller socialMediaObj=socialMeadiaObj.getPoller(obj);
String jobName = (String)obj.get("NAME");
// long rpo =(Long)obj.get("RPO");
JobDetail job = new JobDetail();
job.setName(jobName);
job.setJobClass(Pollersheduller.class);
//configure the scheduler time
SimpleTrigger trigger = new SimpleTrigger();
trigger.setName(jobName);
trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger.setRepeatInterval(12345);
// socialMediaObj.execute();
//schedule it
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.getContext().put("socialMediaObj", socialMediaObj);
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
public void execute(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub
SchedulerContext schedulerContext = null;
try {
schedulerContext = context.getScheduler().getContext();
ISocialMediaPoller socialMediaObj=
(ISocialMediaPoller)schedulerContext.get("socialMediaObj");
socialMediaObj.execute();
} catch (SchedulerException e1) {
e1.printStackTrace();
}
I would suggest managing your jobs through the db , in case your server restarts you better persist the dynamically created quartz jobs.
Here is an example
#Service public class PersistentJobSchedulerJob {
private static Logger logger = Logger.getLogger("PersistentJobSchedulerJob");
#Autowired
private JobRepository jobRepository;
#Autowired
private MailService mailService;
#SuppressWarnings({ "rawtypes", "unchecked" })
#Scheduled(fixedRate=30000)
public void schedulePersistentJobs(){
List<JobData> jobsData= jobRepository.findAll();
logger.info("Retriving Jobs from Database and Scheduling One by One | Total Number of Jobs: "+jobsData.size());
try{
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
for(JobData jobData: jobsData){
JobDetail job = newJob(MailSenderJob.class)
.withIdentity(jobData.getJobName())
.usingJobData(getJobDataMap(jobData))
.build();
if(!jobData.getActive()){
logger.info("Deleting a Job");
scheduler.deleteJob(new JobKey(jobData.getJobName()));
continue;
}
if(scheduler.checkExists(new JobKey(jobData.getJobName()))){
logger.info("Rescheduling the Job");
Trigger oldTrigger = scheduler.getTrigger(new TriggerKey(jobData.getJobName()+"Trigger"));
TriggerBuilder tb = oldTrigger.getTriggerBuilder();
Trigger newTrigger = tb.withSchedule(simpleSchedule()
.withIntervalInMilliseconds(jobData.getRepeatInterval()).
repeatForever())
.build();
scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);
}else{
logger.info("Scheduling the Job");
scheduler.scheduleJob(job,getTrigger(jobData));
}
}
}catch (SchedulerException e) {
logger.error("Scheduler Exception : "+e.getMessage());
}
}
private JobDataMap getJobDataMap(JobData jobData) {
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("recipients", jobData.getRecipients());
jobDataMap.put("mailService", mailService);
return jobDataMap;
}
private Trigger getTrigger(JobData jobData){
SimpleTrigger simpleTrigger = newTrigger().withIdentity(jobData.getJobName()+"Trigger")
.startAt(jobData.getStartDateTime())
.withSchedule(simpleSchedule()
.withIntervalInMilliseconds(jobData.getRepeatInterval()).
repeatForever())
.build();
return simpleTrigger;
} }
The full source code can be found here: Job scheduling with Quartz example
public static void setupSchedule() {
try {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail job = newJob(Reader.class).withIdentity("job1", "group1").build();
String Frequency = Props.getProps().getProperty("BIRTHDAYFREQUENCY");
CronTrigger ct = newTrigger().withIdentity("trigger1", "group1")
.withSchedule(cronSchedule(Frequency)).build();
scheduler.scheduleJob(job, ct);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
If you are asking to implement quartz scheduler in web application then answer is yes.
All you have to do put all scheduler configuration in servlet init method. Like you have done it your question. Init method will be called only once on start-up of application or on first request. So all the configuration and scheduler time will be set at that time. Make sure to include all the quartz dependencies.
private Scheduler scheduler ;
public void init(ServletConfig config) throws ServletException
{
JobKey jobKeyA = new JobKey("jobA", "group1");
JobDetail jobA = JobBuilder.newJob(CallJob.class)
.withIdentity(jobKeyA).build();
//jobA.getJobDataMap().put("queue_setup", queue_setup);
Trigger trigger1 = TriggerBuilder
.newTrigger()
.withIdentity("triggerJobA", "group1")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInMinutes(1).repeatForever()).build();
//runs every minute
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(jobA, trigger1);
}
Job class
public class CallJob implements Job {
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException
{
System.out.println("Yes job is running");
}
}