下面列出了org.quartz.JobKey#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Fill common attributes with properties from context.
*/
public void fillWithContext(JobExecutionContext context) {
startDate = context.getFireTime();
jobClass = Jobs.jobCass(context.getJobDetail()).getName();
JobKey key = context.getJobDetail().getKey();
jobKey = Keys.desc(key);
jobGroup = key.getGroup();
jobName = key.getName();
TriggerKey key2 = context.getTrigger().getKey();
triggerKey = Keys.desc(key2);
triggerGroup = key2.getGroup();
triggerName = key2.getName();
dataMap = JobDataMapUtils.toProperties(context.getMergedJobDataMap());
}
/**
* Add a chain mapping - when the Job identified by the first key completes
* the job identified by the second key will be triggered.
*
* @param firstJob a JobKey with the name and group of the first job
* @param secondJob a JobKey with the name and group of the follow-up job
*/
public void addJobChainLink(JobKey firstJob, JobKey secondJob) {
if(firstJob == null || secondJob == null) {
throw new IllegalArgumentException("Key cannot be null!");
}
if(firstJob.getName() == null || secondJob.getName() == null) {
throw new IllegalArgumentException("Key cannot have a null name!");
}
chainLinks.put(firstJob, secondJob);
}
/**
* Used by {@link QuartzTaskInfo#runNow()}.
*/
@Guarded(by = STARTED)
public void runNow(final String triggerSource,
final JobKey jobKey,
final QuartzTaskInfo taskInfo,
final QuartzTaskState taskState)
throws TaskRemovedException, SchedulerException
{
checkState(active, "Cannot run tasks while scheduler is paused");
TaskConfiguration config = taskState.getConfiguration();
// avoid marking local state as running if task is limited to run on a different node
if (!isLimitedToAnotherNode(config)) {
taskInfo.setNexusTaskState(
RUNNING,
taskState,
new QuartzTaskFuture(
this,
jobKey,
config.getTaskLogName(),
new Date(),
scheduleFactory().now(),
triggerSource
)
);
}
try (TcclBlock tccl = TcclBlock.begin(this)) {
// triggering with dataMap from "now" trigger as it contains metadata for back-conversion in listener
JobDataMap triggerDetail = triggerConverter.convert(scheduleFactory().now()).build().getJobDataMap();
triggerDetail.putAll(filterKeys(config.asMap(), INHERITED_CONFIG_KEYS::contains));
scheduler.triggerJob(jobKey, triggerDetail);
}
catch (JobPersistenceException e) {
throw new TaskRemovedException(jobKey.getName(), e);
}
}
@Override
public void stopJob(JobKey jobKey) throws SchedulerException {
if (!this.scheduler.checkExists(jobKey)) {
throw new IllegalStateException(
"Cannot stop detection pipeline " + jobKey.getName() + ", it has not been scheduled");
}
this.scheduler.deleteJob(jobKey);
LOG.info("Stopped detection pipeline {}", jobKey.getName());
}
private void createExpressionObserverJob(
JobKey jobKey, UUID triggerKey, String configExpression, String cronExpression) throws SchedulerException
{
if (!ClassDeactivationUtils.isActivated(DynamicExpressionObserverJob.class))
{
return;
}
JobKey observerJobKey =
new JobKey(jobKey.getName() + DynamicExpressionObserverJob.OBSERVER_POSTFIX, jobKey.getGroup());
JobDetail jobDetail = JobBuilder.newJob(DynamicExpressionObserverJob.class)
.usingJobData(DynamicExpressionObserverJob.CONFIG_EXPRESSION_KEY, configExpression)
.usingJobData(DynamicExpressionObserverJob.TRIGGER_ID_KEY, triggerKey.toString())
.usingJobData(DynamicExpressionObserverJob.ACTIVE_CRON_EXPRESSION_KEY, cronExpression)
.withDescription("Config observer for: " + jobKey)
.withIdentity(observerJobKey)
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(observerJobKey)
.withSchedule(CronScheduleBuilder.cronSchedule(
SchedulerBaseConfig.JobCustomization.DYNAMIC_EXPRESSION_OBSERVER_INTERVAL))
.build();
this.scheduler.scheduleJob(jobDetail, trigger);
}
public static Long getTaskIdByJobKey(JobKey jobKey) {
String name = jobKey.getName();
return Long.valueOf(StringUtils.replace(name, QuartzConst.JOB_KEY_PREFIX, ""));
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
jobApplication = ApplicationContextHolder.getBean(JobApplication.class);
appApplication = ApplicationContextHolder.getBean(AppApplication.class);
JobKey jobKey = context.getTrigger().getJobKey();
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
JobDto jobDto = jobApplication.getJobInfo(jobName, jobGroup);
if (jobDto == null) {
return;
}
if (JobTypeEnum.ONE_TIME_JOB.getIndex().equals(jobDto.getJobType())) {
jobApplication.deleteJob(jobDto.getId());
}
JobParams jobParams = new JobParams();
BeanUtils.copyProperties(jobDto, jobParams);
jobParams.setJobId(jobDto.getId());
LogDto logDto = new LogDto();
BeanUtils.copyProperties(jobDto, logDto);
logDto.setId(null);
List<String> addressList = appApplication.getAddressList(jobGroup, Boolean.TRUE);
if (CollectionUtils.isEmpty(addressList)) {
addressList = appApplication.getAddressList(jobGroup, Boolean.FALSE);
logDto.setLogType(LogTypeEnum.APP_OFFLINE.getIndex());
logDto.setInfo(CommonUtils.getLogInfo(logDto));
logDto.setStartTime(new Date());
logDto.setEndTime(new Date());
if (CollectionUtils.isNotEmpty(addressList)) {
addressList.forEach(p -> {
logDto.setAddress(p);
ApplicationContextHolder.getLogApplication().recordLogInfo(CommonUtils.getTenantId(logDto.getJobName()), logDto);
});
} else {
logDto.setLogType(LogTypeEnum.APP_OFFLINE.getIndex());
ApplicationContextHolder.getLogApplication().recordLogInfo(CommonUtils.getTenantId(logDto.getJobName()), logDto);
}
return;
}
logDto.setLogType(LogTypeEnum.ADDRESS_INVALID.getIndex());
logger.info("---------Start Executing Job!");
RpcResponse rpcResponse = doExecute(jobParams, addressList, logDto, jobDto.getRouteStrategy(), jobDto.getRetryCount());
logger.info("---------Finish Executing Job!");
logDto.setEndTime(new Date());
if (rpcResponse != null && Result.SUCCESS == rpcResponse.getResult()) {
logDto.setLogType(LogTypeEnum.REQUEST_SEND.getIndex());
} else if (!StringUtils.isEmpty(jobDto.getJobOwner())) {
DefaultThreadPool.executor.submit(new AlarmTask(jobDto));
}
logDto.setInfo(CommonUtils.getLogInfo(logDto));
ApplicationContextHolder.getLogApplication().modifyLogInfo(logDto);
}
/**
* Get all jobs
*/
@Override
public List<Map<String, Object>> getAllJobs() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
Scheduler scheduler = schedulerFactoryBean.getScheduler();
for (String groupName : scheduler.getJobGroupNames()) {
for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
//get job's trigger
List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
Date scheduleTime = triggers.get(0).getStartTime();
Date nextFireTime = triggers.get(0).getNextFireTime();
Date lastFiredTime = triggers.get(0).getPreviousFireTime();
Map<String, Object> map = new HashMap<String, Object>();
map.put("jobName", jobName);
map.put("groupName", jobGroup);
map.put("scheduleTime", scheduleTime);
map.put("lastFiredTime", lastFiredTime);
map.put("nextFireTime", nextFireTime);
if(isJobRunning(jobName)){
map.put("jobStatus", "RUNNING");
}else{
String jobState = getJobState(jobName);
map.put("jobStatus", jobState);
}
/* Date currentDate = new Date();
if (scheduleTime.compareTo(currentDate) > 0) {
map.put("jobStatus", "scheduled");
} else if (scheduleTime.compareTo(currentDate) < 0) {
map.put("jobStatus", "Running");
} else if (scheduleTime.compareTo(currentDate) == 0) {
map.put("jobStatus", "Running");
}*/
list.add(map);
System.out.println("Job details:");
System.out.println("Job Name:"+jobName + ", Group Name:"+ groupName + ", Schedule Time:"+scheduleTime);
}
}
} catch (SchedulerException e) {
System.out.println("SchedulerException while fetching all jobs. error message :"+e.getMessage());
e.printStackTrace();
}
return list;
}
/**
* Get all jobgroups, jobs within this group, the jobdetail and the
* associated triggers in XML format.
*/
public XmlBuilder getJobGroupNamesWithJobsToXml(Scheduler theScheduler, IbisManager ibisManager) {
XmlBuilder xbRoot = new XmlBuilder("jobGroups");
try {
// process groups
List<String> jgnames = theScheduler.getJobGroupNames();
for (int i = 0; i < jgnames.size(); i++) {
XmlBuilder el = new XmlBuilder("jobGroup");
String jobGroupName = jgnames.get(i);
el.addAttribute("name", jobGroupName);
// process jobs within group
XmlBuilder jb = new XmlBuilder("jobs");
Set<JobKey> jobKeys = theScheduler.getJobKeys(GroupMatcher.jobGroupEquals(jobGroupName));
for (JobKey jobKey : jobKeys) {
XmlBuilder jn = new XmlBuilder("job");
String jobName = jobKey.getName();
jn.addAttribute("name", jobName);
// details for job
JobDetail jobDetail = theScheduler.getJobDetail(jobKey);
XmlBuilder jd = jobDetailToXmlBuilder(jobDetail);
jn.addSubElement(jd);
// get the triggers for this job
List<? extends Trigger> triggers = theScheduler.getTriggersOfJob(jobKey);
XmlBuilder tr = getJobTriggers(triggers);
jn.addSubElement(tr);
JobDataMap jobDataMap = jobDetail.getJobDataMap();
XmlBuilder datamap = jobDataMapToXmlBuilder(jobDataMap);
jn.addSubElement(datamap);
jb.addSubElement(jn);
JobDef jobDef = null;
if(ibisManager != null) {
for (Configuration configuration : ibisManager.getConfigurations()) {
jobDef = configuration.getScheduledJob(jobName);
if (jobDef != null) {
break;
}
}
}
XmlBuilder ms = getJobMessages(jobDef);
jn.addSubElement(ms);
XmlBuilder jrs= getJobRunStatistics(jobDef);
jn.addSubElement(jrs);
}
el.addSubElement(jb);
xbRoot.addSubElement(el);
}
} catch (SchedulerException se) {
log.error(se);
}
return xbRoot;
}
private Map<String, Object> getJobData(JobKey jobKey, boolean expanded) throws SchedulerException {
Map<String, Object> jobData = new HashMap<String, Object>();
Scheduler scheduler = getScheduler();
String jobName = jobKey.getName();
JobDetail job = scheduler.getJobDetail(jobKey);
jobData.put("fullName", job.getKey().getGroup() + "." + job.getKey().getName());
jobData.put("name", job.getKey().getName());
jobData.put("group", job.getKey().getGroup());
String description = "-";
if (StringUtils.isNotEmpty(job.getDescription()))
description = job.getDescription();
jobData.put("description", description);
jobData.put("stateful", job.isPersistJobDataAfterExecution() && job.isConcurrentExectionDisallowed());
jobData.put("durable",job.isDurable());
jobData.put("jobClass", job.getJobClass().getSimpleName());
if(job instanceof IbisJobDetail) {
jobData.put("type", ((IbisJobDetail) job).getJobType());
}
TriggerState state = scheduler.getTriggerState(TriggerKey.triggerKey(jobName, jobKey.getGroup()));
jobData.put("state", state.name());
jobData.put("triggers", getJobTriggers(scheduler.getTriggersOfJob(jobKey)));
jobData.put("messages", getJobMessages(job));
JobDataMap jobMap = job.getJobDataMap();
jobData.put("properties", getJobData(jobMap));
if(expanded) {
JobDef jobDef = (JobDef) jobMap.get(ConfiguredJob.JOBDEF_KEY);
jobData.put("adapter", jobDef.getAdapterName());
jobData.put("receiver", jobDef.getReceiverName());
jobData.put("message", jobDef.getMessage());
Locker locker = jobDef.getLocker();
if(locker != null) {
jobData.put("locker", true);
jobData.put("lockkey", locker.getObjectId());
} else {
jobData.put("locker", false);
}
}
return jobData;
}