下面列出了org.quartz.UnableToInterruptJobException#org.quartz.JobKey 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Trigger createTrigger(Scheduled scheduled, JobKey jobKey, String cronExpression) throws SchedulerException
{
UUID triggerKey = UUID.randomUUID();
if (!scheduled.cronExpression().endsWith(cronExpression))
{
createExpressionObserverJob(jobKey, triggerKey, scheduled.cronExpression(), cronExpression);
}
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(jobKey)
.withIdentity(triggerKey.toString())
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
return trigger;
}
/**
* <p>
* Delete the identified <code>Job</code> from the Scheduler - and any
* associated <code>Trigger</code>s.
* </p>
*
* @return true if the Job was found and deleted.
* @throws SchedulerException
* if there is an internal Scheduler error.
*/
public boolean deleteJob(JobKey jobKey) throws SchedulerException {
validateState();
boolean result = false;
List<? extends Trigger> triggers = getTriggersOfJob(jobKey);
for (Trigger trigger : triggers) {
if (!unscheduleJob(trigger.getKey())) {
StringBuilder sb = new StringBuilder().append(
"Unable to unschedule trigger [").append(
trigger.getKey()).append("] while deleting job [")
.append(jobKey).append(
"]");
throw new SchedulerException(sb.toString());
}
result = true;
}
result = resources.getJobStore().removeJob(jobKey) || result;
if (result) {
notifySchedulerThread(0L);
notifySchedulerListenersJobDeleted(jobKey);
}
return result;
}
/**
* <p>
* Update the states of all triggers associated with the given job.
* </p>
*
* @param conn
* the DB Connection
* @param state
* the new state for the triggers
* @return the number of rows updated
*/
public int updateTriggerStatesForJob(Connection conn, JobKey jobKey,
String state) throws SQLException {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(rtp(UPDATE_JOB_TRIGGER_STATES));
ps.setString(1, state);
ps.setString(2, jobKey.getName());
ps.setString(3, jobKey.getGroup());
return ps.executeUpdate();
} finally {
closeStatement(ps);
}
}
/**
* Delete the identified Job from the Scheduler - and any associated Triggers.
*/
@Override
public boolean deleteJob(String jobName) {
System.out.println("Request received for deleting job.");
String jobKey = jobName;
String groupKey = "SampleGroup";
JobKey jkey = new JobKey(jobKey, groupKey);
System.out.println("Parameters received for deleting job : jobKey :"+jobKey);
try {
boolean status = schedulerFactoryBean.getScheduler().deleteJob(jkey);
System.out.println("Job with jobKey :"+jobKey+ " deleted with status :"+status);
return status;
} catch (SchedulerException e) {
System.out.println("SchedulerException while deleting job with key :"+jobKey + " message :"+e.getMessage());
e.printStackTrace();
return false;
}
}
/**
* Returns all tasks for the {@link #GROUP_NAME} group, which also have attached job-listeners.
*/
private Map<JobKey, QuartzTaskInfo> allTasks() throws SchedulerException {
try (TcclBlock tccl = TcclBlock.begin(this)) {
Map<JobKey, QuartzTaskInfo> result = new HashMap<>();
Set<JobKey> jobKeys = scheduler.getJobKeys(jobGroupEquals(GROUP_NAME));
for (JobKey jobKey : jobKeys) {
QuartzTaskJobListener listener = findJobListener(jobKey);
if (listener != null) {
result.put(jobKey, listener.getTaskInfo());
}
else {
// TODO: Sort out if this is normal or edge-case indicative of a bug or not
log.debug("Job missing listener; omitting from results: {}", jobKey);
}
}
return result;
}
}
public static JobDetailImpl createJobDetail(
String measureJson,
String predicatesJson) {
JobDetailImpl jobDetail = new JobDetailImpl();
JobKey jobKey = new JobKey("name", "group");
jobDetail.setKey(jobKey);
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put(MEASURE_KEY, measureJson);
jobDataMap.put(PREDICATES_KEY, predicatesJson);
jobDataMap.put(JOB_NAME, "jobName");
jobDataMap.put("jobName", "jobName");
jobDataMap.put(PREDICATE_JOB_NAME, "predicateJobName");
jobDataMap.put(GRIFFIN_JOB_ID, 1L);
jobDetail.setJobDataMap(jobDataMap);
return jobDetail;
}
@GET
@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
@Path("/schedules/{groupName}/job/{jobName}")
@Relation("schedules")
@Produces(MediaType.APPLICATION_JSON)
public Response getSchedule(@PathParam("jobName") String jobName, @PathParam("groupName") String groupName) throws ApiException {
Map<String, Object> returnMap = new HashMap<String, Object>();
JobKey jobKey = JobKey.jobKey(jobName, groupName);
try {
returnMap = getJobData(jobKey, true);
} catch (SchedulerException e) {
throw new ApiException(e);
}
return Response.status(Response.Status.OK).entity(returnMap).build();
}
/**
* Start a job now
*/
@Override
public boolean startJobNow(String jobName) {
System.out.println("Request received for starting job now.");
String jobKey = jobName;
String groupKey = "SampleGroup";
JobKey jKey = new JobKey(jobKey, groupKey);
System.out.println("Parameters received for starting job now : jobKey :"+jobKey);
try {
schedulerFactoryBean.getScheduler().triggerJob(jKey);
System.out.println("Job with jobKey :"+jobKey+ " started now succesfully.");
return true;
} catch (SchedulerException e) {
System.out.println("SchedulerException while starting job now with key :"+jobKey+ " message :"+e.getMessage());
e.printStackTrace();
return false;
}
}
@GetMapping(URL_LIST)
@SuppressWarnings("unchecked")
public List<Map<String, String>> listScheduledJobs() throws SchedulerException {
List<Map<String, String>> jobs = new LinkedList<>();
SiteContext siteContext = SiteContext.getCurrent();
Scheduler scheduler = siteContext.getScheduler();
if(scheduler != null) {
List<String> groups = scheduler.getJobGroupNames();
for (String group : groups) {
Set<JobKey> keys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(group));
for (JobKey key : keys) {
List<Trigger> triggers = (List<Trigger>)scheduler.getTriggersOfJob(key);
Map<String, String> job = new HashMap<>();
job.put("name", key.getName());
job.put("nextFireTime", triggers.get(0).getNextFireTime().toInstant().toString());
jobs.add(job);
}
}
}
return jobs;
}
/**
* <p>
* Calls the equivalent method on the 'proxied' <code>QuartzScheduler</code>,
* passing the <code>SchedulingContext</code> associated with this
* instance.
* </p>
*/
public void resumeJobs(GroupMatcher<JobKey> matcher) throws SchedulerException {
String operation = null;
switch (matcher.getCompareWithOperator()) {
case EQUALS:
operation = "resumeJobGroup";
break;
case STARTS_WITH:
operation = "resumeJobsStartingWith";
break;
case ENDS_WITH:
operation = "resumeJobsEndingWith";
break;
case CONTAINS:
operation = "resumeJobsContaining";
case ANYTHING:
operation = "resumeJobsAll";
}
invoke(
operation,
new Object[] { matcher.getCompareToValue() },
new String[] { String.class.getName() });
}
/**
* Pause a job
*/
@Override
public boolean pauseJob(String jobName) {
System.out.println("Request received for pausing job.");
String jobKey = jobName;
String groupKey = "SampleGroup";
JobKey jkey = new JobKey(jobKey, groupKey);
System.out.println("Parameters received for pausing job : jobKey :"+jobKey+ ", groupKey :"+groupKey);
try {
schedulerFactoryBean.getScheduler().pauseJob(jkey);
System.out.println("Job with jobKey :"+jobKey+ " paused succesfully.");
return true;
} catch (SchedulerException e) {
System.out.println("SchedulerException while pausing job with key :"+jobName + " message :"+e.getMessage());
e.printStackTrace();
return false;
}
}
public void schedule(Runnable r, String cronExpression, boolean longRunning) {
try {
JobDataMap jdm = new JobDataMap();
jdm.put(RunnableRunner.KEY_RUNNABLE_OBJECT, r);
jdm.put(RunnableRunner.KEY_PROPERTY_IS_LONGRUNNING_TASK, longRunning);
jdm.put(RunnableRunner.KEY_CRON_EXPRESSION, cronExpression);
String jobId = "Started at ms" + System.currentTimeMillis() + "; ns" + System.nanoTime();
JobKey jobKey = new JobKey("JobKey:" + jobId);
JobDetail jobDetail = JobBuilder.newJob(runnableRunner).usingJobData(jdm).withIdentity(jobKey).build();
CronScheduleBuilder csb = CronScheduleBuilder.cronSchedule(cronExpression);
CronTrigger trigger = TriggerBuilder.newTrigger().withSchedule(csb).build();
scheduler.scheduleJob(jobDetail, trigger);
} catch (Exception e) {
throw new CronServiceException("Failed to start job", e);
}
}
/**
* This method runs the current job only once, right now
* @return int 0 if it's not running, 1 if it is, 2 if there is an error
*/
public int getSelectedJobRunning()
{
Scheduler scheduler = schedulerManager.getScheduler();
if (scheduler == null)
{
log.error("Scheduler is down!");
return 2;
}
try
{
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
JobKey selected = selectedJobDetailWrapper.getJobDetail().getKey();
for (JobExecutionContext jobExecutionContext : executingJobs) {
if(selected.equals(jobExecutionContext.getJobDetail().getKey()) )
return 1;
}
return 0;
}
catch (Exception e)
{
log.error("Failed to trigger job now", e);
return 2;
}
}
/**
* all states: BLOCKED COMPLETE ERROR NONE NORMAL PAUSED
* to start states: PAUSED
* to stop states: BLOCKED NORMAL
*
* @param job streaming job
*/
@Override
public void start(AbstractJob job) {
String name = job.getName();
String group = job.getGroup();
TriggerState state = getTriggerState(name, group);
if (state == null) {
throw new GriffinException.BadRequestException(
JOB_IS_NOT_SCHEDULED);
}
/* If job is not in paused state,we can't start it
as it may be RUNNING.*/
if (state != PAUSED) {
throw new GriffinException.BadRequestException
(JOB_IS_NOT_IN_PAUSED_STATUS);
}
JobKey jobKey = jobKey(name, group);
try {
factory.getScheduler().resumeJob(jobKey);
} catch (SchedulerException e) {
throw new GriffinException.ServiceException(
"Failed to start job.", e);
}
}
@Override
public Map<IJobKey, CrontabEntry> getScheduledJobs() {
// NOTE: no synchronization is needed here since this is just a dump of internal quartz state
// for debugging.
ImmutableMap.Builder<IJobKey, CrontabEntry> scheduledJobs = ImmutableMap.builder();
try {
for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.anyGroup())) {
// The quartz API allows jobs to have multiple triggers. We don't use that feature but
// we're defensive here since this function is used for debugging.
Optional<CronTrigger> trigger = FluentIterable.from(scheduler.getTriggersOfJob(jobKey))
.filter(CronTrigger.class)
.first()
.toJavaUtil();
if (trigger.isPresent()) {
scheduledJobs.put(
Quartz.auroraJobKey(jobKey),
Quartz.crontabEntry(trigger.get()));
}
}
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
return scheduledJobs.build();
}
public void resumeJobs(final GroupMatcher<JobKey> matcher) {
try {
scheduler.resumeJobs(matcher);
} catch (final SchedulerException e) {
throw new QuartzSchedulerException(e);
}
}
/**
* <p>
* Remove (delete) the <code>{@link org.quartz.Job}</code> with the given name, and any
* <code>{@link org.quartz.Trigger}</code> s that reference it.
* </p>
*
* @param jobKey The key of the <code>Job</code> to be removed.
* @return <code>true</code> if a <code>Job</code> with the given name & group was found and removed from the store.
*/
@Override
public boolean removeJob(JobKey jobKey) throws JobPersistenceException {
boolean found = false;
lock();
try {
List<OperableTrigger> trigger = getTriggersForJob(jobKey);
for (OperableTrigger trig : trigger) {
this.removeTrigger(trig.getKey());
found = true;
}
found = (jobFacade.remove(jobKey) != null) | found;
if (found) {
Set<String> grpSet = toolkitDSHolder.getOrCreateJobsGroupMap(jobKey.getGroup());
grpSet.remove(jobKey.getName());
if (grpSet.isEmpty()) {
toolkitDSHolder.removeJobsGroupMap(jobKey.getGroup());
jobFacade.removeGroup(jobKey.getGroup());
}
}
} finally {
unlock();
}
return found;
}
@Override
protected Triple<JobType, String, String> getReference(final JobKey jobKey) {
String key = JobNamer.getTaskKeyFromJobName(jobKey.getName());
Task task = taskDAO.find(key);
return task == null || !(task instanceof SchedTask)
? null
: Triple.of(JobType.TASK, key, binder.buildRefDesc(task));
}
@Override
public boolean removeJobs(final List<JobKey> jobKeys) throws JobPersistenceException {
log.debug("Remove jobs: {}", jobKeys);
return executeWrite(db -> {
boolean allDeleted = true;
for (JobKey key : jobKeys) {
allDeleted = removeJob(db, key) && allDeleted;
}
return allDeleted;
});
}
@Override
public synchronized void startup(String group, String name) {
JobKey jobKey = JobKey.jobKey(name, group);
ScheduleStatus scheduleStatus = jobStatusMap.get(getUniqueId(jobKey));
if (scheduleStatus == null || scheduleStatus == ScheduleStatus.SHUTDOWN) {
LoggerHelper.info("job [" + group + "," + name + "] now is shutdown ,begin startup.");
startupJob(jobKey);
} else if (scheduleStatus == ScheduleStatus.PAUSE) {
LoggerHelper.info("job [" + group + "," + name + "] now is pause ,begin resume.");
resumeJob(jobKey);
} else {
LoggerHelper.warn("job [" + group + "," + name + "] has been startup, skip.");
}
jobStatusMap.put(getUniqueId(jobKey), ScheduleStatus.STARTUP);
}
public List<Matcher<JobKey>> getJobListenerMatchers(String listenerName) {
synchronized (globalJobListeners) {
List<Matcher<JobKey>> matchers = globalJobListenersMatchers.get(listenerName);
if(matchers == null)
return null;
return Collections.unmodifiableList(matchers);
}
}
@Override
public void pauseJob(JobKey jobKey) throws JobPersistenceException {
String jobHashKey = createJobHashKey(jobKey.getGroup(),jobKey.getName());
try (Jedis jedis = pool.getResource()) {
lockPool.acquire();
pauseJob(jobHashKey, jedis);
} catch (Exception ex) {
log.error("could not pause job: " + jobHashKey, ex);
throw new JobPersistenceException(ex.getMessage(), ex.getCause());
} finally {
lockPool.release();
}
}
public List<? extends Trigger> getTriggersOfJob(final JobKey jobKey) {
try {
return scheduler.getTriggersOfJob(jobKey);
} catch (final SchedulerException e) {
throw new QuartzSchedulerException(e);
}
}
public <T> void schedule(JobResourceAdapter<T> resource) {
JobDetail jobDetail = buildJobDetail(resource.getLocalId(), resource.getRemoteResourceId(), resource.getJobClassForResource());
Trigger trigger = buildJobTrigger(jobDetail);
try {
if (scheduler.getJobDetail(JobKey.jobKey(resource.getLocalId(), JOB_GROUP)) != null) {
unschedule(resource.getLocalId());
}
scheduler.scheduleJob(jobDetail, trigger);
} catch (SchedulerException e) {
LOGGER.error(String.format("Error during scheduling quartz job: %s", resource.getLocalId()), e);
}
}
protected void setAllTriggersOfJobToState(JobKey jobKey, int state) {
ArrayList<TriggerWrapper> tws = getTriggerWrappersForJob(jobKey);
for (TriggerWrapper tw : tws) {
tw.state = state;
if (state != TriggerWrapper.STATE_WAITING) {
timeTriggers.remove(tw);
}
}
}
@Test
@SuppressWarnings("unchecked")
public void testExecute() throws Exception {
JobExecutionContext context = mock(JobExecutionContext.class);
Scheduler scheduler = mock(Scheduler.class);
GriffinMeasure measure = createGriffinMeasure("measureName");
JobDetail jd = createJobDetail(JsonUtil.toJson(measure), "");
BatchJob job = new BatchJob(1L, "jobName",
"qName", "qGroup", false);
job.setConfigMap(new HashMap<>());
List<Trigger> triggers = Arrays.asList(createSimpleTrigger(2, 0));
given(context.getJobDetail()).willReturn(jd);
given(measureRepo.findOne(Matchers.anyLong())).willReturn(measure);
given(repo.findOne(Matchers.anyLong())).willReturn(job);
given(factory.getScheduler()).willReturn(scheduler);
given((List<Trigger>) scheduler.getTriggersOfJob(Matchers.any(
JobKey.class))).willReturn(triggers);
given(scheduler.checkExists(Matchers.any(TriggerKey.class)))
.willReturn(false);
given(jobRepo.save(Matchers.any(BatchJob.class))).willReturn(job);
given(scheduler.checkExists(Matchers.any(JobKey.class)))
.willReturn(false);
Trigger trigger = mock(Trigger.class);
given(context.getTrigger()).willReturn(trigger);
given(trigger.getKey()).willReturn(new TriggerKey("test"));
jobInstance.execute(context);
verify(measureRepo, times(1)).findOne(Matchers.anyLong());
verify(factory, times(4)).getScheduler();
verify(scheduler, times(1)).getTriggersOfJob(Matchers.any(
JobKey.class));
}
public static DetectionPipelineTaskInfo buildTaskInfo(JobExecutionContext jobExecutionContext) {
JobKey jobKey = jobExecutionContext.getJobDetail().getKey();
Long id = getIdFromJobKey(jobKey.getName());
DetectionConfigDTO configDTO = DAORegistry.getInstance().getDetectionConfigManager().findById(id);
return buildTaskInfoFromDetectionConfig(configDTO, System.currentTimeMillis());
}
/**
* Delete all quartz scheduler jobs of the group <code>Dropbox</code>.
*/
private void cancelAllJobs() {
try {
Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
Set<JobKey> jobKeys = sched.getJobKeys(jobGroupEquals(SCHEDULER_GROUP));
if (jobKeys.size() > 0) {
sched.deleteJobs(new ArrayList<JobKey>(jobKeys));
logger.debug("Found {} DB4O-Jobs to delete from DefaultScheduler (keys={})", jobKeys.size(), jobKeys);
}
} catch (SchedulerException e) {
logger.warn("Couldn't remove Commit-Job: {}", e.getMessage());
}
}
/**
* 编辑&启停定时任务
* @throws SchedulerException
*/
@Override
public boolean editAndScheduleJob(QuartzJob quartzJob) throws SchedulerException {
if (CommonConstant.STATUS_NORMAL.equals(quartzJob.getStatus())) {
schedulerDelete(quartzJob.getJobClassName().trim());
schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());
}else{
scheduler.pauseJob(JobKey.jobKey(quartzJob.getJobClassName().trim()));
}
return this.updateById(quartzJob);
}
@Override
public void pauseJob(JobKey jobKey) throws JobPersistenceException {
try {
realJobStore.pauseJob(jobKey);
} catch (RejoinException e) {
throw new JobPersistenceException("Pausing job failed due to client rejoin", e);
}
}