use of org.quartz.JobPersistenceException in project weicoder by wdcode.
the class StdJDBCDelegate method selectTrigger.
/**
* <p>
* Select a trigger.
* </p>
*
* @param conn
* the DB Connection
* @return the <code>{@link org.quartz.Trigger}</code> object
* @throws JobPersistenceException
*/
public OperableTrigger selectTrigger(Connection conn, TriggerKey triggerKey) throws SQLException, ClassNotFoundException, IOException, JobPersistenceException {
PreparedStatement ps = null;
ResultSet rs = null;
try {
OperableTrigger trigger = null;
ps = conn.prepareStatement(rtp(SELECT_TRIGGER));
ps.setString(1, triggerKey.getName());
ps.setString(2, triggerKey.getGroup());
rs = ps.executeQuery();
if (rs.next()) {
String jobName = rs.getString(COL_JOB_NAME);
String jobGroup = rs.getString(COL_JOB_GROUP);
String description = rs.getString(COL_DESCRIPTION);
long nextFireTime = rs.getLong(COL_NEXT_FIRE_TIME);
long prevFireTime = rs.getLong(COL_PREV_FIRE_TIME);
String triggerType = rs.getString(COL_TRIGGER_TYPE);
long startTime = rs.getLong(COL_START_TIME);
long endTime = rs.getLong(COL_END_TIME);
String calendarName = rs.getString(COL_CALENDAR_NAME);
int misFireInstr = rs.getInt(COL_MISFIRE_INSTRUCTION);
int priority = rs.getInt(COL_PRIORITY);
Map<?, ?> map = null;
if (canUseProperties()) {
map = getMapFromProperties(rs);
} else {
map = (Map<?, ?>) getObjectFromBlob(rs, COL_JOB_DATAMAP);
}
Date nft = null;
if (nextFireTime > 0) {
nft = new Date(nextFireTime);
}
Date pft = null;
if (prevFireTime > 0) {
pft = new Date(prevFireTime);
}
Date startTimeD = new Date(startTime);
Date endTimeD = null;
if (endTime > 0) {
endTimeD = new Date(endTime);
}
if (triggerType.equals(TTYPE_BLOB)) {
rs.close();
rs = null;
ps.close();
ps = null;
ps = conn.prepareStatement(rtp(SELECT_BLOB_TRIGGER));
ps.setString(1, triggerKey.getName());
ps.setString(2, triggerKey.getGroup());
rs = ps.executeQuery();
if (rs.next()) {
trigger = (OperableTrigger) getObjectFromBlob(rs, COL_BLOB);
}
} else {
TriggerPersistenceDelegate tDel = findTriggerPersistenceDelegate(triggerType);
if (tDel == null)
throw new JobPersistenceException("No TriggerPersistenceDelegate for trigger discriminator type: " + triggerType);
TriggerPropertyBundle triggerProps = null;
try {
triggerProps = tDel.loadExtendedTriggerProperties(conn, triggerKey);
} catch (IllegalStateException isex) {
if (isTriggerStillPresent(ps)) {
throw isex;
} else {
// QTZ-386 Trigger has been deleted
return null;
}
}
TriggerBuilder<?> tb = newTrigger().withDescription(description).withPriority(priority).startAt(startTimeD).endAt(endTimeD).withIdentity(triggerKey).modifiedByCalendar(calendarName).withSchedule(triggerProps.getScheduleBuilder()).forJob(jobKey(jobName, jobGroup));
if (null != map) {
tb.usingJobData(new JobDataMap(map));
}
trigger = (OperableTrigger) tb.build();
trigger.setMisfireInstruction(misFireInstr);
trigger.setNextFireTime(nft);
trigger.setPreviousFireTime(pft);
setTriggerStateProperties(trigger, triggerProps);
}
}
return trigger;
} finally {
closeResultSet(rs);
closeStatement(ps);
}
}
use of org.quartz.JobPersistenceException in project weicoder by wdcode.
the class QuartzSchedulerThread method run.
/**
* <p>
* The main processing loop of the <code>QuartzSchedulerThread</code>.
* </p>
*/
@Override
public void run() {
int acquiresFailed = 0;
while (!halted.get()) {
try {
// check if we're supposed to pause...
synchronized (sigLock) {
while (paused && !halted.get()) {
try {
// wait until togglePause(false) is called...
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
// reset failure counter when paused, so that we don't
// wait again after unpausing
acquiresFailed = 0;
}
if (halted.get()) {
break;
}
}
// failing (e.g. DB is down or restarting)..
if (acquiresFailed > 1) {
try {
long delay = computeDelayForRepeatedErrors(qsRsrcs.getJobStore(), acquiresFailed);
Thread.sleep(delay);
} catch (Exception ignore) {
}
}
int availThreadCount = qsRsrcs.getThreadPool().blockForAvailableThreads();
if (availThreadCount > 0) {
// will always be true, due to semantics of blockForAvailableThreads...
List<OperableTrigger> triggers;
long now = System.currentTimeMillis();
clearSignaledSchedulingChange();
try {
triggers = qsRsrcs.getJobStore().acquireNextTriggers(now + idleWaitTime, Math.min(availThreadCount, qsRsrcs.getMaxBatchSize()), qsRsrcs.getBatchTimeWindow());
acquiresFailed = 0;
if (log.isDebugEnabled())
log.debug("batch acquisition of " + (triggers == null ? 0 : triggers.size()) + " triggers");
} catch (JobPersistenceException jpe) {
if (acquiresFailed == 0) {
qs.notifySchedulerListenersError("An error occurred while scanning for the next triggers to fire.", jpe);
}
if (acquiresFailed < Integer.MAX_VALUE)
acquiresFailed++;
continue;
} catch (RuntimeException e) {
if (acquiresFailed == 0) {
getLog().error("quartzSchedulerThreadLoop: RuntimeException " + e.getMessage(), e);
}
if (acquiresFailed < Integer.MAX_VALUE)
acquiresFailed++;
continue;
}
if (triggers != null && !triggers.isEmpty()) {
now = System.currentTimeMillis();
long triggerTime = triggers.get(0).getNextFireTime().getTime();
long timeUntilTrigger = triggerTime - now;
while (timeUntilTrigger > 2) {
synchronized (sigLock) {
if (halted.get()) {
break;
}
if (!isCandidateNewTimeEarlierWithinReason(triggerTime, false)) {
try {
// we could have blocked a long while
// on 'synchronize', so we must recompute
now = System.currentTimeMillis();
timeUntilTrigger = triggerTime - now;
if (timeUntilTrigger >= 1)
sigLock.wait(timeUntilTrigger);
} catch (InterruptedException ignore) {
}
}
}
if (releaseIfScheduleChangedSignificantly(triggers, triggerTime)) {
break;
}
now = System.currentTimeMillis();
timeUntilTrigger = triggerTime - now;
}
// this happens if releaseIfScheduleChangedSignificantly decided to release triggers
if (triggers.isEmpty())
continue;
// set triggers to 'executing'
List<TriggerFiredResult> bndles = new ArrayList<TriggerFiredResult>();
boolean goAhead = true;
synchronized (sigLock) {
goAhead = !halted.get();
}
if (goAhead) {
try {
List<TriggerFiredResult> res = qsRsrcs.getJobStore().triggersFired(triggers);
if (res != null)
bndles = res;
} catch (SchedulerException se) {
qs.notifySchedulerListenersError("An error occurred while firing triggers '" + triggers + "'", se);
// we release them and loop again
for (int i = 0; i < triggers.size(); i++) {
qsRsrcs.getJobStore().releaseAcquiredTrigger(triggers.get(i));
}
continue;
}
}
for (int i = 0; i < bndles.size(); i++) {
TriggerFiredResult result = bndles.get(i);
TriggerFiredBundle bndle = result.getTriggerFiredBundle();
Exception exception = result.getException();
if (exception instanceof RuntimeException) {
getLog().error("RuntimeException while firing trigger " + triggers.get(i), exception);
qsRsrcs.getJobStore().releaseAcquiredTrigger(triggers.get(i));
continue;
}
// fired at this time... or if the scheduler was shutdown (halted)
if (bndle == null) {
qsRsrcs.getJobStore().releaseAcquiredTrigger(triggers.get(i));
continue;
}
JobRunShell shell = null;
try {
shell = qsRsrcs.getJobRunShellFactory().createJobRunShell(bndle);
shell.initialize(qs);
} catch (SchedulerException se) {
qsRsrcs.getJobStore().triggeredJobComplete(triggers.get(i), bndle.getJobDetail(), CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR);
continue;
}
if (qsRsrcs.getThreadPool().runInThread(shell) == false) {
// this case should never happen, as it is indicative of the
// scheduler being shutdown or a bug in the thread pool or
// a thread pool being used concurrently - which the docs
// say not to do...
getLog().error("ThreadPool.runInThread() return false!");
qsRsrcs.getJobStore().triggeredJobComplete(triggers.get(i), bndle.getJobDetail(), CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR);
}
}
// while (!halted)
continue;
}
} else {
// while (!halted)
continue;
}
long now = System.currentTimeMillis();
long waitTime = now + getRandomizedIdleWaitTime();
long timeUntilContinue = waitTime - now;
synchronized (sigLock) {
try {
if (!halted.get()) {
// scheduled very soon
if (!isScheduleChanged()) {
sigLock.wait(timeUntilContinue);
}
}
} catch (InterruptedException ignore) {
}
}
} catch (RuntimeException re) {
getLog().error("Runtime error occurred in main trigger firing loop.", re);
}
}
// while (!halted)
// drop references to scheduler stuff to aid garbage collection...
qs = null;
qsRsrcs = null;
}
use of org.quartz.JobPersistenceException in project jbpm by kiegroup.
the class QuartzSchedulerService method internalSchedule.
@Override
public void internalSchedule(TimerJobInstance timerJobInstance) {
GlobalQuartzJobHandle quartzJobHandle = (GlobalQuartzJobHandle) timerJobInstance.getJobHandle();
// Define job instance
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("timerJobInstance", timerJobInstance);
JobDetail jobq = newJob(QuartzJob.class).withIdentity(quartzJobHandle.getJobName(), quartzJobHandle.getJobGroup()).requestRecovery().usingJobData(new JobDataMap(dataMap)).build();
// Amend nextFireTime not to schedule older than now + RESCHEDULE_DELAY
Date nextFireTime = timerJobInstance.getTrigger().hasNextFireTime();
Date threshold = new Date(System.currentTimeMillis() + RESCHEDULE_DELAY);
if (nextFireTime.before(threshold)) {
logger.debug("nextFireTime [" + nextFireTime + "] is older than (now + RESCHEDULE_DELAY). Amending it to [" + threshold + "]");
nextFireTime = threshold;
}
// Define a Trigger that will fire "now"
org.quartz.Trigger triggerq = newTrigger().withIdentity(quartzJobHandle.getJobName() + "_trigger", quartzJobHandle.getJobGroup()).startAt(nextFireTime).build();
// nextFireTime is mapped to startTime
logger.debug("triggerq.name = {}, triggerq.startTime = {}", triggerq.getKey().getName(), triggerq.getStartTime());
// Schedule the job with the trigger
try {
if (scheduler.isShutdown()) {
return;
}
globalTimerService.getTimerJobFactoryManager().addTimerJobInstance(timerJobInstance);
JobDetail jobDetail = scheduler.getJobDetail(jobKey(quartzJobHandle.getJobName(), quartzJobHandle.getJobGroup()));
if (jobDetail == null) {
scheduler.scheduleJob(jobq, triggerq);
} else {
// need to add the job again to replace existing especially important if jobs are persisted in db
scheduler.addJob(jobq, true, true);
scheduler.rescheduleJob(triggerq.getKey(), triggerq);
}
} catch (ObjectAlreadyExistsException e) {
// in general this should not happen even in clustered environment but just in case
// already registered jobs should be caught in scheduleJob but due to race conditions it might not
// catch it in time - clustered deployments only
logger.warn("Job has already been scheduled, most likely running in cluster: {}", e.getMessage());
} catch (JobPersistenceException e) {
if (e.getCause() instanceof NotSerializableException) {
// in case job cannot be persisted, like rule timer then make it in memory
internalSchedule(new InmemoryTimerJobInstanceDelegate(quartzJobHandle.getJobName(), ((GlobalTimerService) globalTimerService).getTimerServiceId()));
} else {
globalTimerService.getTimerJobFactoryManager().removeTimerJobInstance(timerJobInstance);
throw new RuntimeException(e);
}
} catch (SchedulerException e) {
globalTimerService.getTimerJobFactoryManager().removeTimerJobInstance(timerJobInstance);
throw new RuntimeException("Exception while scheduling job", e);
}
}
use of org.quartz.JobPersistenceException in project weicoder by wdcode.
the class JobStoreSupport method storeCalendar.
protected void storeCalendar(Connection conn, String calName, Calendar calendar, boolean replaceExisting, boolean updateTriggers) throws JobPersistenceException {
try {
boolean existingCal = calendarExists(conn, calName);
if (existingCal && !replaceExisting) {
throw new ObjectAlreadyExistsException("Calendar with name '" + calName + "' already exists.");
}
if (existingCal) {
if (getDelegate().updateCalendar(conn, calName, calendar) < 1) {
throw new JobPersistenceException("Couldn't store calendar. Update failed.");
}
if (updateTriggers) {
List<OperableTrigger> trigs = getDelegate().selectTriggersForCalendar(conn, calName);
for (OperableTrigger trigger : trigs) {
trigger.updateWithNewCalendar(calendar, getMisfireThreshold());
storeTrigger(conn, trigger, null, true, STATE_WAITING, false, false);
}
}
} else {
if (getDelegate().insertCalendar(conn, calName, calendar) < 1) {
throw new JobPersistenceException("Couldn't store calendar. Insert failed.");
}
}
if (!isClustered) {
// lazy-cache
calendarCache.put(calName, calendar);
}
} catch (IOException e) {
throw new JobPersistenceException("Couldn't store calendar because the BLOB couldn't be serialized: " + e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new JobPersistenceException("Couldn't store calendar: " + e.getMessage(), e);
} catch (SQLException e) {
throw new JobPersistenceException("Couldn't store calendar: " + e.getMessage(), e);
}
}
use of org.quartz.JobPersistenceException in project weicoder by wdcode.
the class JobStoreSupport method resumeTrigger.
/**
* <p>
* Resume (un-pause) the <code>{@link org.quartz.Trigger}</code> with the given name.
* </p>
* <p>
* If the <code>Trigger</code> missed one or more fire-times, then the <code>Trigger</code>'s misfire instruction will
* be applied.
* </p>
*
* @see #pauseTrigger(Connection, TriggerKey)
*/
public void resumeTrigger(Connection conn, TriggerKey key) throws JobPersistenceException {
try {
TriggerStatus status = getDelegate().selectTriggerStatus(conn, key);
if (status == null || status.getNextFireTime() == null) {
return;
}
boolean blocked = false;
if (STATE_PAUSED_BLOCKED.equals(status.getStatus())) {
blocked = true;
}
String newState = checkBlockedState(conn, status.getJobKey(), STATE_WAITING);
boolean misfired = false;
if (schedulerRunning && status.getNextFireTime().before(new Date())) {
misfired = updateMisfiredTrigger(conn, key, newState, true);
}
if (!misfired) {
if (blocked) {
getDelegate().updateTriggerStateFromOtherState(conn, key, newState, STATE_PAUSED_BLOCKED);
} else {
getDelegate().updateTriggerStateFromOtherState(conn, key, newState, STATE_PAUSED);
}
}
} catch (SQLException e) {
throw new JobPersistenceException("Couldn't resume trigger '" + key + "': " + e.getMessage(), e);
}
}
Aggregations