I am learning quartz scheduler framework and as a base I have started with "Hello World" thats prints at regular Intervals.
This is my SampleScheduler
public class SampleScheduler {
public static void main(String arfs[]) {
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
System.out.println("Scheduler Started...");
JobDetail job = new JobDetail("job1","group1",SampleJobInter.class);
Trigger trigger = new SimpleTrigger("trigger1",Scheduler.DEFAULT_GROUP,new Date(),null,SimpleTrigger.REPEAT_INDEFINITELY,60L*1000L);
scheduler.scheduleJob(job, trigger);
scheduler.shutdown();
System.out.println("Scheduler Stopped..");
} catch(SchedulerException e) {
}
}
}
Here is my SampleJobInter.class
public class SampleJobInter implements Job {
SampleJobInter(){}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println("Hello World at "+new Date());
}
}
The output am getting is
Scheduler Started...
Scheduler Stopped..
I am not getting the desired output. I am running it in the console. Do I need to do any configurations or what?. Please Help me in this
just put scheduler.start() after you have scheduled a job to run - scheduler.scheduleJob...
UPDATE: I stand corrected by org.life.java. The order of statements won't make much of a difference. The source of your troubles is the shutdown() invocation. A scheduler's contract [javadoc] is to keep running as long as an explicit shutdown command is not issued on it. if you remove that line from your code, it works fine.
I have created it from scratch and it works well.!!
I would suggest you to compare your code with this ans also log exception in catch so that you will have good idea.
JobRunner
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.life.java.so.questions;
/**
*
* #author Jigar
*/
import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
public class HelloSchedule {
public HelloSchedule() throws Exception {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
sched.start();
JobDetail jd = new JobDetail("myjob", sched.DEFAULT_GROUP, SampleJobInter.class);
SimpleTrigger st = new SimpleTrigger("mytrigger", sched.DEFAULT_GROUP, new Date(),
null, SimpleTrigger.REPEAT_INDEFINITELY, 100L);
sched.scheduleJob(jd, st);
}
public static void main(String args[]) {
try {
new HelloSchedule();
} catch (Exception e) {
}
}
}
Job
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.life.java.so.questions;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
*
* #author Jigar
*/
public class SampleJobInter implements Job {
public SampleJobInter() {
}
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Hello World at " + new Date());
}
}
Related
I'm using Quartz in stand alone jar. Added that in SET ENV PRE_CLASSPATH of Weblogic 12.2.1.3. Configured Startup Class. Cron parameter is dynamically passed from a DB Table. Till that it is fine. But I want to change the cron parameter in db table so that Quartz takes that and changes the schedule timing dynamically AT RUNTIME itself. Problem is, I have to restart weblogic to take that effect. Because Quartz is checking the DB parameter at server start time only. How to get that working in real time?
package com.adac.scheduler.service;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class QuartzFTPPush implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("This is a Job That is Scheduled At "+new Date());
}
}
package com.adac.scheduler.service;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;
import java.sql.*;
public class QuartzFTPPushCronTrigger {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:AGPOS/yed6_4aN#10.6.6.11:1532:AGPTST");
Statement stmt=con.createStatement();
//ResultSet rs=stmt.executeQuery("SELECT DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD, DB_SID, DB_TABLE from AG_RSD_SCHEDULE_MAS_TBL");
ResultSet rs = stmt.executeQuery("Select cron_schedule from AG_RSD_SCHEDULE_MAS_TBL where company_id=5");
/*
* while(rs.next())
* System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
*/
rs.next();
String cron_schedule = rs.getString(1);
con.close();
final JobKey jobKey = new JobKey("QuartzFTPPushName", "group1");
final JobDetail job = JobBuilder.newJob(QuartzFTPPush.class).withIdentity(jobKey).build();
//final String cron_schedule = "0/5 * * * * ?";
//final Trigger trigger = TriggerBuilder.newTrigger().withIdentity("QuartzFTPPushTriggerName", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build();
final Trigger trigger = TriggerBuilder.newTrigger().withIdentity("QuartzFTPPushTriggerName", "group1").withSchedule(CronScheduleBuilder.cronSchedule(cron_schedule)).build();
final Scheduler scheduler = new StdSchedulerFactory().getScheduler();
// Listener attached to jobKey
scheduler.getListenerManager().addJobListener(new QuartzFTPPushListener(), KeyMatcher.keyEquals(jobKey));
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
package com.adac.scheduler.service;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
public class QuartzFTPPushListener implements JobListener {
public String getName() {
return "QuartzFTPPushListener";
}
public void jobToBeExecuted(JobExecutionContext context) {
final String jobName = context.getJobDetail().getKey().toString();
System.out.println("jobToBeExecuted: " + jobName + " is starting...");
}
public void jobExecutionVetoed(JobExecutionContext context) {
System.out.println("jobExecutionVetoed");
}
public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
System.out.println("jobWasExecuted");
final String jobName = context.getJobDetail().getKey().toString();
System.out.println("Job : " + jobName + " is finished!!");
if (!jobException.getMessage().equals("")) {
System.out.println("Exception thrown by: " + jobName + " Exception: " + jobException.getMessage());
}
}
}
Select cron_schedule from "AG_RSD_SCHEDULE_MAS_TBL" where company_id=5;
The output of above query is 0/10 * * * * ?. I want to change that to some other value, let's say 0/5 * * * * ?. And want Quartz to schedule with same without restarting weblogic.
Please suggest.
I'm trying to test my network module. When I run this on simulator or device, handler is ok, but when I'm trying to do it from tests, handler = null and callback doesn't get called. How can I solve this problem?
public void performCall(Call callToPerform){
callToPerform.call.enqueue(new okhttp3.Callback() {
Handler handler = new Handler();
#Override
public void onFailure(okhttp3.Call call, IOException e) {
handler.post(() -> {
for (Callback callback : callToPerform.callbacks) {
callback.onFailure(callToPerform, e);
}
});
}
#Override
public void onResponse(okhttp3.Call call, final okhttp3.Response response){
handler.post(() -> {
for (Callback callback : callToPerform.callbacks) {
try {
callback.onResponse(callToPerform, new Response(response.body().bytes(), response.headers().toMultimap()));
} catch (IOException e) {
callback.onFailure(call, e);
}
}
});
}
});
}
My graddle app file contains this params.
testOptions {
unitTests.returnDefaultValues = true
}
Ok, after a few hours of research I've found solution and it's similar to this:
package com.dpmedeiros.androidtestsupportlibrary;
import android.os.Handler;
import android.os.Looper;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.*;
/**
* Utility methods that unit tests can use to do common android library mocking that might be needed.
*/
public class AndroidMockUtil {
private AndroidMockUtil() {}
/**
* Mocks main thread handler post() and postDelayed() for use in Android unit tests
*
* To use this:
* <ol>
* <li>Call this method in an {#literal #}Before method of your test.</li>
* <li>Place Looper.class in the {#literal #}PrepareForTest annotation before your test class.</li>
* <li>any class under test that needs to call {#code new Handler(Looper.getMainLooper())} should be placed
* in the {#literal #}PrepareForTest annotation as well.</li>
* </ol>
*
* #throws Exception
*/
public static void mockMainThreadHandler() throws Exception {
PowerMockito.mockStatic(Looper.class);
Looper mockMainThreadLooper = mock(Looper.class);
when(Looper.getMainLooper()).thenReturn(mockMainThreadLooper);
Handler mockMainThreadHandler = mock(Handler.class);
Answer<Boolean> handlerPostAnswer = new Answer<Boolean>() {
#Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Runnable runnable = invocation.getArgumentAt(0, Runnable.class);
Long delay = 0L;
if (invocation.getArguments().length > 1) {
delay = invocation.getArgumentAt(1, Long.class);
}
if (runnable != null) {
mainThread.schedule(runnable, delay, TimeUnit.MILLISECONDS);
}
return true;
}
};
doAnswer(handlerPostAnswer).when(mockMainThreadHandler).post(any(Runnable.class));
doAnswer(handlerPostAnswer).when(mockMainThreadHandler).postDelayed(any(Runnable.class), anyLong());
PowerMockito.whenNew(Handler.class).withArguments(mockMainThreadLooper).thenReturn(mockMainThreadHandler);
}
private final static ScheduledExecutorService mainThread = Executors.newSingleThreadScheduledExecutor();
}
If you run this sample code on JUnit, this will not work because JUnit tests are running on a JVM, and Instrumented tests are running on a Simulator or Real Device
You can take a look at this link, it explains why :
Instrumented tests or Local tests
I want to create multiple threads on Java, and allot each thread a separate Quartz scheduler. But the only way I can find is to create multiple .properties files, for each separate scheduler. As I have a huge number of threads, creating so many properties files isn't feasible. Is there a better way to do so?
Please use this concept to handle multiple scheduler threads for multiple task on the basis of dynamic parameter
/*
* Date : 2015-07-06
* Author : Bhuwan Prasad Upadhyay
*/
package com.developerbhuwan.quartzexample;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
/**
*
* #author developerbhuwan
*/
public class MutlipleScheduleThread {
public static void main(String[] args) {
new MutlipleScheduleThread().createMultipleThread();
}
private void createMultipleThread() {
for (int i = 0; i <= 10; i++) { //create 10 scheduler thread to perform different job on the basis of param
try {
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put(MyJob.KEY_PARAM, "ParamValue");
JobKey jobKey = new JobKey("UniqueJobId" + i, "JobGroup");
JobDetail job = JobBuilder
.newJob(MyJob.class)
.withIdentity(jobKey)
.setJobData(jobDataMap)
.storeDurably(true)
.build();
TriggerKey triggerKey = new TriggerKey("UniqueTriggerID" + i, "TriggerGroup");
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity(triggerKey)
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 1/1 * ? *")) //every one hour
.forJob(job)
.build();
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException ex) {
Logger.getLogger(MutlipleScheduleThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private static class MyJob implements Job {
private static String KEY_PARAM = "param";
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String param = dataMap.getString(KEY_PARAM);
//do job on the basis of parameter
}
}
}
Source Code Quartz Example
Hi I've been trying all night to run this example and have had no luck what so ever, I cannot find a solution. I have two file.
First is Worker.java and here is its contents
import javafx.application.Application;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author brett
*/
public class Worker {
/**
* #param args the command line arguments
* #throws java.lang.Exception
*/
/**
*
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
doit();
}
private static void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
mytask.call();
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Next is the IteratingTask.java file and its contents
//import javafx.concurrent.Task;
import javafx.application.Application;
import javafx.concurrent.Task;
/**
*
* #author brett
*/
public class IteratingTask extends Task<Integer> {
private final int totalIterations;
public IteratingTask(int totalIterations) {
this.totalIterations = totalIterations;
}
#Override protected Integer call() throws Exception {
int iterations;
// iterations = 0;
for (iterations = 0; iterations < totalIterations; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, totalIterations);
}
return iterations;
}
}
I know I'm doing something very wrong but... I just cant see it.
Here is the error it get
run:
Jan 31, 2015 11:56:38 PM Worker doit
SEVERE: null
java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:270)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:265)
at javafx.application.Platform.runLater(Platform.java:81)
at javafx.concurrent.Task.runLater(Task.java:1211)
at javafx.concurrent.Task.updateMessage(Task.java:1129)
at IteratingTask.call(IteratingTask.java:24)
at Worker.doit(Worker.java:38)
at Worker.main(Worker.java:31)
BUILD SUCCESSFUL (total time: 0 seconds)
It builds ok.... any advice would be awesome.
The problem is that the FX Toolkit, and in particular the FX Application Thread have not been started. The update...(...) methods in Task update various state on the FX Application Thread, so your calls to those methods cause an IllegalStateException as there is no such thread running.
If you embed this code in an actual FX Application, it will run fine. Calling launch() causes the FX toolkit to be started.
Also, note that while this will run, Tasks are generally intended to be run in a background thread, as below:
import javafx.application.Application;
import javafx.scene.Scene ;
import javafx.scene.layout.StackPane ;
import javafx.scene.control.Label ;
import javafx.stage.Stage ;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Worker extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane(new Label("Hello World"));
Scene scene = new Scene(root, 350, 75);
primaryStage.setScene(scene);
primaryStage.show();
doit();
}
public static void main(String[] args) throws Exception {
launch(args);
}
private void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
// mytask.call();
Thread backgroundThread = new Thread(mytask);
backgroundThread.start(); // will return immediately, task runs in background
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
For example, I want to write a Java program to print "Hello World" at each day 12 am, how can I use Quartz scheduler to achieve this?
Trigger trigger = TriggerUtils.makeDailyTrigger(0, 0);
trigger.setName("trigger1");
trigger.setGroup("group1");
Like this? Where should I put print "hello world" method?
You could use an expression to schedule the execution of the job. e.g.:
public static class HelloJob implements Job {
#Override
public void execute(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("Hello World");
}
}
public static void main(String[] args) throws SchedulerException {
String exp = "0 0 0 1/1 * ? *";
SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
scheduler.start();
JobDetail job = JobBuilder.newJob(HelloJob.class).build();
Trigger trigger = TriggerBuilder.newTrigger()
.startNow()
.withSchedule(
CronScheduleBuilder.cronSchedule(exp))
.build();
scheduler.scheduleJob(job, trigger);
}
See http://www.cronmaker.com/ for build another expression. e.g. 0 0/1 * 1/1 * ? * every minute for to see the output. See also Cron Expressions.
Download quartz Jar Put in lib folder build project
Create Class (Job) from which you want to schedule task
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyJob implements Job {
private Logger log = Logger.getLogger(MyJob.class);
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
log.debug("Hi....");
System.out.println("Corn Executing.....");
}
}
Create Class for schedule your task
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class JobScheduler {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("myjob").build();
Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(30).repeatForever()).build();
SchedulerFactory schFactory = new StdSchedulerFactory();
Scheduler scheduler = schFactory.getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}catch (SchedulerException e) {
e.printStackTrace();
}
}
}
You have to create your custom job by implementing Job interface and providing your implementation of execute method.In execute method you can print "hello world". Then you can schedule your job like this
scheduler.scheduleJob(job, trigger);
Refer this link for step by step details:
Quartz tutorial
you can create cron expression for this. to have quartz job you need to have following objects
Job
Task which will be associated to a Job
Finally create a trigger and associate a Job to the trigger
Triggers of two type
Simple triggers, where you can control job , you can run every min or 10 mins and so on. you can also have additional parameters
initial delay - to kick off
repeatcount - no of times the job should be executes, if -1 then job will be executed infinitely
In your case you can use cron triggers since you want to run every day at 12 am.
For more details and sample program look at this below link
http://www.mkyong.com/spring/spring-quartz-scheduler-example/
and about quartz cron expression , see the quartz documentation
http://quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger