下面列出了org.quartz.JobExecutionContext#getJobDetail ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void executeInternal(JobExecutionContext context) {
String jobName = null;
try {
JobDetail jobDetail = context.getJobDetail();
JobParameters jobParams = new JobParameters();
if (jobDetail instanceof JobParamsDetail) {
jobParams = JobParamUtil.convertRawToJobParams(((JobParamsDetail) jobDetail).getRawJobParameters());
}
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
jobName = dataMap.getString(JOB_NAME);
JobLocator jobLocator = (JobLocator) context.getScheduler().getContext().get(JOB_LOCATOR);
JobLauncher jobLauncher = (JobLauncher) context.getScheduler().getContext().get(JOB_LAUNCHER);
Job job = jobLocator.getJob(jobName);
log.info("Starting {}", job.getName());
JobExecution jobExecution = jobLauncher.run(job, jobParams);
log.info("{}_{} was completed successfully", job.getName(), jobExecution.getId());
} catch (Exception e) {
log.error("Job {} failed", jobName, e);
}
}
@Override
public void jobWasExecuted(JobExecutionContext context, JobExecutionException exception) {
JobExecution execution = CurrentJobExecution.get();
if (exception != null) {
execution.error();
JobDetail jobDetail = context.getJobDetail();
JobLogs.error("Exception occurred while executing job "
+ Jobs.jobCass(jobDetail).getName(), exception);
}
executions.jobEnds(execution, context);
JobLogs.setDefaultLevel();
CurrentJobExecution.unset();
CurrentJobExecutionContext.unset();
}
private final void interruptRunningJobs() throws SchedulerException {
for(final JobExecutionContext jobExecutionContext : this.scheduler.getCurrentlyExecutingJobs()) {
final JobDetail jobDetail = jobExecutionContext.getJobDetail();
if(LOGGER.isInfoEnabled()) {
LOGGER.info(String.format(
"Interrupting job '%s' of group='%s'.",
jobDetail.getKey().getName(),
jobDetail.getKey().getGroup()));
}
scheduler.interrupt(jobDetail.getKey());
}
}
@Override
public void execute(JobExecutionContext context) {
JobDetail jd = context.getJobDetail();
try {
if (isNeedLivyQueue) {
//livy batch limit
livyTaskSubmitHelper.addTaskToWaitingQueue(jd);
} else {
saveJobInstance(jd);
}
} catch (Exception e) {
LOGGER.error("Post spark task ERROR.", e);
}
}
private void initParam(JobExecutionContext context)
throws SchedulerException {
mPredicates = new ArrayList<>();
JobDetail jobDetail = context.getJobDetail();
Long jobId = jobDetail.getJobDataMap().getLong(GRIFFIN_JOB_ID);
job = jobRepo.findOne(jobId);
Long measureId = job.getMeasureId();
measure = measureRepo.findOne(measureId);
setJobStartTime(jobDetail);
if (job.getConfigMap() == null) {
job.setConfigMap(new HashMap<>());
}
job.getConfigMap().put(TRIGGER_KEY, context.getTrigger().getKey().toString());
}
public ScheduleLogRequest(JobExecutionContext jobExecutionContext, JobExecutionException jobExecutionException) {
JobDetail jobDetail = jobExecutionContext.getJobDetail();
this.className = jobDetail.getKey().getName();
this.application = jobDetail.getKey().getGroup();
this.node = jobDetail.getDescription();
this.type = jobExecutionContext.getTrigger().getDescription();
this.elapsed = jobExecutionContext.getJobRunTime();
this.fireTime = jobExecutionContext.getFireTime();
if (null != jobExecutionException) {
this.stackTrace = ExceptionUtils.getStackTrace(jobExecutionException);
this.success = false;
} else {
this.success = true;
}
}
public void execute(JobExecutionContext context) throws JobExecutionException {
initContext();
auto = true;
JobDetail aJob = context.getJobDetail();
String jobName = aJob.getKey().getName();
JobDataMap dataMap = aJob.getJobDataMap();
String jobConfig = (String) dataMap.get(jobName);
Long jobID = (Long) dataMap.get(jobName + "-ID");
log.info("Job[" + jobName + "] starting...");
excuting(jobName, jobConfig, jobID);
}
/**
* Interrupt all instances of the identified InterruptableJob executing in
* this Scheduler instance.
*
* <p>
* This method is not cluster aware. That is, it will only interrupt
* instances of the identified InterruptableJob currently executing in this
* Scheduler instance, not across the entire cluster.
* </p>
*
* @see org.quartz.core.RemotableQuartzScheduler#interrupt(JobKey)
*/
public boolean interrupt(JobKey jobKey) throws UnableToInterruptJobException {
List<JobExecutionContext> jobs = getCurrentlyExecutingJobs();
JobDetail jobDetail = null;
Job job = null;
boolean interrupted = false;
for(JobExecutionContext jec : jobs) {
jobDetail = jec.getJobDetail();
if (jobKey.equals(jobDetail.getKey())) {
job = jec.getJobInstance();
if (job instanceof InterruptableJob) {
((InterruptableJob)job).interrupt();
interrupted = true;
} else {
throw new UnableToInterruptJobException(
"Job " + jobDetail.getKey() +
" can not be interrupted, since it does not implement " +
InterruptableJob.class.getName());
}
}
}
return interrupted;
}
protected void setTenant(JobExecutionContext jobExecutionContext) throws JobExecutionException {
logger.debug("IN");
JobDetail jobDetail = jobExecutionContext.getJobDetail();
Tenant tenant;
try {
tenant = DAOFactory.getSchedulerDAO().findTenant(jobDetail);
} catch (Throwable t) {
logger.error("Cannot retrieve tenant for job " + jobDetail.toString(), t);
throw new SpagoBIRuntimeException("Cannot retrieve tenant for job " + jobDetail.toString(), t);
}
logger.debug("Tenant : " + tenant);
TenantManager.setTenant(tenant);
logger.debug("OUT");
}
public List<ScheduleJob> getRunningJobList() throws SchedulerException{
List<JobExecutionContext> executingJobList = scheduler.getCurrentlyExecutingJobs();
List<ScheduleJob> jobList = new ArrayList<>(executingJobList.size());
for(JobExecutionContext executingJob : executingJobList){
ScheduleJob scheduleJob = new ScheduleJob();
JobDetail jobDetail = executingJob.getJobDetail();
JobKey jobKey = jobDetail.getKey();
Trigger trigger = executingJob.getTrigger();
this.wrapScheduleJob(scheduleJob,scheduler,jobKey,trigger);
jobList.add(scheduleJob);
}
return jobList;
}
public void execute(JobExecutionContext context) throws JobExecutionException {
DetectionJobDetail jobDetail=(DetectionJobDetail)context.getJobDetail();
Session session=jobDetail.getSessionFactory().openSession();
try {
String currentInstanceName=jobDetail.getCurrentInstanceName();
Operation operation=detection(session,jobDetail.getJobInstanceNames(),currentInstanceName);
if(operation.equals(Operation.reset)){
SchedulerService service=jobDetail.getSchedulerService();
service.resetScheduer();
Heartbeat beat=new Heartbeat();
Calendar c=Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.SECOND, 1);
beat.setDate(c.getTime());
beat.setId(UUID.randomUUID().toString());
beat.setInstanceName(currentInstanceName);
session.save(beat);
initHeartJob(currentInstanceName, service.getScheduler());
}
} catch (Exception e) {
throw new JobExecutionException(e);
}finally{
session.flush();
session.close();
}
}
public void execute(JobExecutionContext context) throws JobExecutionException {
HeartJobDetail detail=(HeartJobDetail)context.getJobDetail();
String instanceName=detail.getCurrentInstanceName();
Session session=detail.getSessionFactory().openSession();
try{
String hql="from "+Heartbeat.class.getName()+" b where b.instanceName=:instanceName order by b.date desc";
Query query=session.createQuery(hql).setString("instanceName",instanceName);
@SuppressWarnings("unchecked")
List<Heartbeat> beats=query.list();
Date now=new Date();
Heartbeat beat=null;
if(beats.size()>0){
beat=beats.get(0);
}else{
beat=new Heartbeat();
beat.setId(UUID.randomUUID().toString());
beat.setInstanceName(instanceName);
}
beat.setDate(now);
session.saveOrUpdate(beat);
}catch(Exception ex){
throw new JobExecutionException(ex);
}finally{
session.flush();
session.close();
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDetail detail = context.getJobDetail();
JobDataMap data = context.getJobDetail().getJobDataMap();
String name = detail.getKey().getName();
String desc = detail.getDescription();
System.err.println("Job fired: " + name + " (" + desc + ")");
if (data != null && data.size() > 0) {
for (String key : data.keySet()) {
System.err.println(" " + key + " = " + data.getString(key));
}
}
}
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
JobDetail jobDetail = context.getJobDetail();
Object params = jobDetail.getJobDataMap().get(QuartzConst.QUARTZ_PARAMS_KEY);
JobKey jobKey = jobDetail.getKey();
Long taskId = SmartQuartzUtil.getTaskIdByJobKey(jobKey);
QuartzTaskService quartzTaskService = (QuartzTaskService) SmartApplicationContext.getBean("quartzTaskService");
QuartzTaskEntity quartzTaskEntity = quartzTaskService.getByTaskId(taskId);
QuartzTaskLogService quartzTaskLogService = (QuartzTaskLogService) SmartApplicationContext.getBean("quartzTaskLogService");
QuartzTaskLogEntity taskLogEntity = new QuartzTaskLogEntity();
taskLogEntity.setTaskId(taskId);
taskLogEntity.setIpAddress(SmartIPUtil.getLocalHostIP());
taskLogEntity.setTaskName(quartzTaskEntity.getTaskName());
String paramsStr = null;
if (params != null) {
paramsStr = params.toString();
taskLogEntity.setTaskParams(paramsStr);
}
taskLogEntity.setUpdateTime(new Date());
taskLogEntity.setCreateTime(new Date());
//任务开始时间
long startTime = System.currentTimeMillis();
try {
ITask taskClass = (ITask) SmartApplicationContext.getBean(quartzTaskEntity.getTaskBean());
taskClass.execute(paramsStr);
taskLogEntity.setProcessStatus(TaskResultEnum.SUCCESS.getStatus());
} catch (Exception e) {
log.error("", e);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
pw.flush();
sw.flush();
taskLogEntity.setProcessStatus(TaskResultEnum.FAIL.getStatus());
taskLogEntity.setProcessLog(sw.toString());
} finally {
long times = System.currentTimeMillis() - startTime;
taskLogEntity.setProcessDuration(times);
quartzTaskLogService.save(taskLogEntity);
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDetail detail = context.getJobDetail();
String name = detail.getJobDataMap().getString("name");
System.out.println("say hello to " + name + " at " + new Date());
}
public void execute(JobExecutionContext context) throws JobExecutionException {
ReminderJobDetail jobDetail=(ReminderJobDetail)context.getJobDetail();
ReminderHandler handler=jobDetail.getReminderHandlerBean();
handler.execute(jobDetail.getProcessInstance(), jobDetail.getTask());
}
public JobDetail getContextJobDetail(JobExecutionContext context) {
return context.getJobDetail();
}
@Override
public JobDetail getContextJobDetail(JobExecutionContext context) {
return context.getJobDetail();
}
private void info (EVENTTYPE eventType, Trigger trig, JobExecutionContext context, JobExecutionException exception, CompletedExecutionInstruction instructionCode) {
JobDetail
detail = (context != null)?context.getJobDetail():null;
final JobDataMap
dataMap = (context != null)?context.getMergedJobDataMap():null;
final String
jobName = (detail != null)?detail.getKey().getName():null,
jobDesc = (detail != null)?detail.getDescription():null;
final Class
jobClass = (detail != null)?detail.getJobClass():null;
final Trigger
trigger = (trig != null)?trig:((context != null)?context.getTrigger():null);
final String
trigName = (trigger != null)?trigger.getKey().getName():null,
trigDesc = (trigger != null)?trigger.getDescription():null;
final Date
trigStart = (trigger != null)?trigger.getStartTime():null,
trigEnd = (trigger != null)?trigger.getEndTime():null;
StringBuilder
sb = new StringBuilder();
switch (eventType)
{
case JOB_EXECUTING:
{
sb.append("Job Executing: [");
sb.append("name: ").append(jobName).append(", description: ").append((jobDesc != null)?jobDesc:"")
.append(", class: ").append(jobClass.getName());
sb.append("]");
break;
}
case JOB_VETOED:
{
sb.append("Job Vetoed: [");
sb.append("name: ").append(jobName).append(", description: ").append((jobDesc != null)?jobDesc:"")
.append(", class: ").append(jobClass.getName());
break;
}
case JOB_EXECUTED:
{
sb.append("Job Executed: [");
sb.append("name: ").append(jobName).append(", description: ").append((jobDesc != null)?jobDesc:"")
.append(", class: ").append(jobClass.getName());
if (exception != null)
{
sb.append (", exception: ").append(exception.getMessage());
if (exception.getCause() != null)
{
sb.append(", exception cause: ").append(exception.getCause().getClass().getName());
}
}
sb.append("]");
break;
}
case TRIGGER_FIRED:
{
sb.append("Trigger Fired: [");
sb.append("trigger: ").append(trigName).append(", trigger description: ").append((trigDesc != null)?trigDesc:"")
.append(", start: ").append((trigStart != null)?trigStart.toString():null)
.append(", end: ").append((trigEnd != null)?trigEnd.toString():null);
sb.append(", job: ").append(jobName).append(", job description: ").append((jobDesc != null)?jobDesc:"")
.append(", class: ").append(jobClass.getName());
sb.append("]");
break;
}
case TRIGGER_MISFIRED:
{
sb.append("Trigger Misfired: [");
sb.append("trigger: ").append(trigName).append(", trigger description: ").append((trigDesc != null)?trigDesc:"")
.append(", start: ").append((trigStart!=null)?trigStart.toString():null)
.append(", end: ").append((trigEnd!=null)?trigEnd.toString():null);
sb.append("]");
break;
}
case TRIGGER_COMPLETED:
{
sb.append("Trigger Completed: [");
sb.append("trigger: ").append(trigName).append(", trigger description: ").append((trigDesc != null)?trigDesc:"")
.append(", start: ").append((trigStart!=null)?trigStart.toString():null)
.append(", end: ").append((trigEnd!=null)?trigEnd.toString():null);
sb.append(", job: ").append(jobName).append(", job description: ").append((jobDesc != null)?jobDesc:"")
.append(", class: ").append(jobClass.getName())
.append(", execution result: ").append(instructionCode);
sb.append("]");
break;
}
}
if (log.isDebugEnabled())
{
log.debug(sb.toString());
}
}
public void execute(final JobExecutionContext jobCtx)
throws JobExecutionException {
Connection conn = null;
Session sess = null;
MessageProducer producer = null;
try {
final JobDetail detail = jobCtx.getJobDetail();
final JobDataMap dataMap = detail.getJobDataMap();
final Context namingCtx = JmsHelper.getInitialContext(dataMap);
final ConnectionFactory connFactory = (ConnectionFactory) namingCtx
.lookup(dataMap
.getString(JmsHelper.JMS_CONNECTION_FACTORY_JNDI));
if (!JmsHelper.isDestinationSecure(dataMap)) {
conn = connFactory.createConnection();
} else {
final String user = dataMap.getString(JmsHelper.JMS_USER);
final String password = dataMap
.getString(JmsHelper.JMS_PASSWORD);
conn = connFactory.createConnection(user, password);
}
final boolean useTransaction = JmsHelper.useTransaction(dataMap);
final int ackMode = dataMap.getInt(JmsHelper.JMS_ACK_MODE);
sess = conn.createSession(useTransaction, ackMode);
final Destination destination = (Destination) namingCtx
.lookup(dataMap.getString(JmsHelper.JMS_DESTINATION_JNDI));
producer = sess.createProducer(destination);
final String msgFactoryClassName = dataMap
.getString(JmsHelper.JMS_MSG_FACTORY_CLASS_NAME);
final JmsMessageFactory messageFactory = JmsHelper
.getMessageFactory(msgFactoryClassName);
final Message msg = messageFactory.createMessage(dataMap, sess);
producer.send(msg);
} catch (final Exception e) {
throw new JobExecutionException(e);
} finally {
JmsHelper.closeResource(producer);
JmsHelper.closeResource(sess);
JmsHelper.closeResource(conn);
}
}