protected void executeInternal(JobExecutionContext context) throws JobExecutionException { try { SchedulerContext schCtx = context.getScheduler().getContext(); // 获取Spring中的上下文 ApplicationContext appCtx = (ApplicationContext) schCtx.get("applicationContext"); this.staticPageSvc = (StaticPageSvc) appCtx.getBean("staticPageSvc"); JobDataMap jdm = context.getJobDetail().getJobDataMap(); // 获取栏目 String channelIdStr = (String) jdm.get(CmsTask.TASK_PARAM_CHANNEL_ID); if (!StringUtils.isBlank(channelIdStr)) { this.channelId = Integer.parseInt(channelIdStr); if (channelId.equals(0)) { channelId = null; } } // 获取站点 String siteIdStr = (String) jdm.get(CmsTask.TASK_PARAM_SITE_ID); if (!StringUtils.isBlank(siteIdStr)) { this.siteId = Integer.parseInt(siteIdStr); } } catch (SchedulerException e1) { // TODO 尚未处理异常 e1.printStackTrace(); } staitcChannel(); }
@Override public synchronized void jobToBeExecuted(JobExecutionContext jec) { if (processBusiness == null) { this.processBusiness = SpringHelper.getBean(IProcessBusiness.class); } final Job job = jec.getJobInstance(); if (!(job instanceof ProcessJob)) return; // attach a listener on the process final ProcessJob pj = (ProcessJob) job; final ProcessJobDetail detail = (ProcessJobDetail) jec.getJobDetail(); final QuartzTask quartzTask = (QuartzTask) detail.getJobDataMap().get(QuartzJobListener.PROPERTY_TASK); final String quartzTaskId = quartzTask.getId(); final Task taskEntity = new Task(); taskEntity.setIdentifier(UUID.randomUUID().toString()); taskEntity.setState(TaskState.PENDING.name()); taskEntity.setTaskParameterId(quartzTask.getTaskParameterId()); taskEntity.setOwner(quartzTask.getUserId()); taskEntity.setType(""); // TODO processBusiness.addTask(taskEntity); final ProcessListener listener = new StateListener(taskEntity.getIdentifier(), quartzTask.getTitle()); pj.addListener(listener); LOGGER.log(Level.INFO, "Run task " + taskEntity.getIdentifier()); }
public void execute(final JobExecutionContext jobExecutionContext) throws JobExecutionException { try { if (getBlockoutManager().shouldFireNow() || isBlockoutAction( jobExecutionContext)) { // We should always let the blockouts fire //$NON-NLS-1$ final long start = System.currentTimeMillis(); makeAuditRecord(0, MessageTypes.INSTANCE_START, jobExecutionContext); createUnderlyingJob().execute(jobExecutionContext); final long end = System.currentTimeMillis(); makeAuditRecord( ((float) (end - start) / 1000), MessageTypes.INSTANCE_END, jobExecutionContext); } else { getLogger() .warn( "Job '" + jobExecutionContext.getJobDetail().getName() + "' attempted to run during a blockout period. This job was not executed"); } } catch (SchedulerException e) { getLogger() .warn( "Got Exception retrieving the Blockout Manager for job '" + jobExecutionContext.getJobDetail().getName() + "'. Executing the underlying job anyway", e); createUnderlyingJob().execute(jobExecutionContext); } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { if (checklistNotificationsUri == null) { return; } boolean started = !HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().isActive(); if (started) { HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().begin(); } try { URI researchObjectUri = (URI) context.getMergedJobDataMap().get(RESEARCH_OBJECT_URI); SyndFeedInput input = new SyndFeedInput(); URI requestedUri = createQueryUri(getTheLastFeedDate(researchObjectUri), researchObjectUri); try { context.setResult(input.build(new XmlReader(requestedUri.toURL()))); } catch (IllegalArgumentException | FeedException | IOException e) { LOGGER.error("Can't get the feed " + requestedUri.toString()); } } finally { if (started) { HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); } } }
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap(); AbstractMessageReceiver receiver = (AbstractMessageReceiver) map.get(QuartzMessageReceiver.QUARTZ_RECEIVER_PROPERTY); Object payload = jobExecutionContext.getJobDetail().getJobDataMap().get(QuartzConnector.PROPERTY_PAYLOAD); try { if (payload == null) { String ref = jobExecutionContext .getJobDetail() .getJobDataMap() .getString(QuartzConnector.PROPERTY_PAYLOAD_REFERENCE); // for backward compatibility check the old payload Class property too if (ref == null) { ref = jobExecutionContext .getJobDetail() .getJobDataMap() .getString(QuartzConnector.PROPERTY_PAYLOAD_CLASS_NAME); } try { payload = MuleManager.getInstance().getContainerContext().getComponent(ref); } catch (ObjectNotFoundException e) { logger.warn("There is no payload attached to this quartz job. Sending Null payload"); payload = new NullPayload(); } } receiver.routeMessage(new MuleMessage(receiver.getConnector().getMessageAdapter(payload))); } catch (Exception e) { receiver.handleException(e); } }
/* * (non-Javadoc) * * @see org.quartz.JobListener#jobWasExecuted(org.quartz.JobExecutionContext, org.quartz.JobExecutionException) */ @Override public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { String jobName = context.getJobDetail().getKey().getName(); final BatchSchedule sch = batchSerivce.findSchById(jobName); final JobExecution job = (JobExecution) context.get(CapBatchConstants.K_JobExecution); if (sch != null && job != null) { if (sch.isNotify() && !CapString.isEmpty(sch.getNotifyStatus()) && !CapString.isEmpty(sch.getNotifyTo())) { for (String status : sch.getNotifyStatus().split(",")) { if (CapString.trimNull(status).equals(job.getExitStatus().getExitCode())) { // 主旨 String subject = MessageFormat.format( mailSubject, new Object[] { sch.getSchId(), sch.getSchDesc(), job.getExitStatus().getExitCode() }); mailSender.sendEmail(sch.getNotifyTo().split(","), subject, buildText(job)); break; } } } } }
private int insertJobDetail(Connection conn, JobExecutionContext context) throws IOException, SQLException, SchedulerException { JobDetail job = context.getJobDetail(); JobDataMap jobDataMap = job.getJobDataMap(); Object oResult = context.getResult(); ByteArrayOutputStream baos = serializeJobData(jobDataMap); ByteArrayOutputStream baosResult = serializeObject(oResult); PreparedStatement ps = null; int insertResult = 0; try { ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL_TRACK, scheduler.getSchedulerName())); ps.setString(1, job.getKey().getName()); ps.setString(2, job.getKey().getGroup()); String instanceId = context.getFireInstanceId(); ps.setString(3, instanceId); ps.setString(4, job.getDescription()); ps.setString(5, job.getJobClass().getName()); // TODO verify it works with DB2v8 // DB2v8 : ps.setInt(6, ((job.isDurable()) ? 1 : 0)); ps.setBoolean(6, job.isDurable()); // TODO verify it works with DB2v8 // DB2v8 : ps.setInt(7, ((job.isConcurrentExectionDisallowed()) ? 1 : 0)); ps.setBoolean(7, job.isConcurrentExectionDisallowed()); // TODO verify it works with DB2v8 // DB2v8 : ps.setInt(8, ((job.isPersistJobDataAfterExecution()) ? 1 : 0)); ps.setBoolean(8, job.isPersistJobDataAfterExecution()); // TODO verify it works with DB2v8 // DB2v8 : ps.setInt(9, ((job.requestsRecovery()) ? 1 : 0)); ps.setBoolean(9, job.requestsRecovery()); // TODO verify it works with Sybase // Sybase : ps.setBytes(10, (baos == null) ? null: baos.toByteArray()); ps.setBytes(10, (baos == null) ? new byte[0] : baos.toByteArray()); ps.setBytes(11, (baosResult == null) ? new byte[0] : baosResult.toByteArray()); String restartedInstanceId = jobDataMap.getString(RESTARTED_FIRE_INSTANCE_ID); ps.setString(12, restartedInstanceId); String returnCode = null; if (oResult instanceof JobDataMap) { returnCode = ((JobDataMap) oResult).getString(QuartzContextAdapter.RETURN_CODE); } else { returnCode = String.valueOf(oResult); } ps.setString(13, returnCode); insertResult = ps.executeUpdate(); } finally { closeStatement(ps); cleanupConnection(conn); } return insertResult; }
protected void makeAuditRecord( final float time, final String messageType, final JobExecutionContext jobExecutionContext) { if (jobExecutionContext != null && jobExecutionContext.getJobDetail() != null) { final JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap(); AuditHelper.audit( PentahoSessionHolder.getSession() != null ? PentahoSessionHolder.getSession().getId() : null, jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER) != null ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER).toString() : null, jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER) != null ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER).toString() : null, jobExecutionContext.getJobDetail().getJobClass() != null ? jobExecutionContext.getJobDetail().getJobClass().getName() : null, jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID) != null ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID).toString() : null, messageType, jobDataMap.get("lineage-id") != null ? jobDataMap.get("lineage-id").toString() : null, null, time, null); //$NON-NLS-1$ } }
public void execute(JobExecutionContext _context) throws JobExecutionException { String cacheId = (String) _context.getJobDetail().getJobDataMap().get("cacheId"); IWriteCache c = CacheManager.getWrite2DBCache(cacheId); List<ArkContent> list = c.getAll(); c.clear(); System.out.println("job-" + _context.getJobDetail().getName() + " execute..." + list.size()); ISession session = null; try { if (false) { if (list != null && list.size() > 0) { session = LocalContextHelper.currentSession(); for (Iterator<ArkContent> iterator = list.iterator(); iterator.hasNext(); ) { session.save(iterator.next()); } } } } catch (Exception e) { logger.error("error when write arkcontent to DB.", e); } finally { if (session != null) try { session.close(); } catch (PureException e) { logger.error("error when close session.", e); } if (list != null) list.clear(); } }
/** * Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>{@link org.quartz.Trigger} * </code> fires that is associated with the <code>Job</code>. * * @throws JobExecutionException if there is an exception while executing the job. */ public void execute(JobExecutionContext context) throws JobExecutionException { // This job simply prints out its job name and the // date and time that it is running JobKey jobKey = context.getJobDetail().getKey(); // Grab and print passed parameters JobDataMap data = context.getJobDetail().getJobDataMap(); String favoriteColor = data.getString(FAVORITE_COLOR); int count = data.getInt(EXECUTION_COUNT); _log.info( "ColorJob: " + jobKey + " executing at " + new Date() + "\n" + " favorite color is " + favoriteColor + "\n" + " execution count (from job map) is " + count + "\n" + " execution count (from job member variable) is " + _counter); // increment the count and store it back into the // job map so that job state can be properly maintained count++; data.put(EXECUTION_COUNT, count); // Increment the local member variable // This serves no real purpose since job state can not // be maintained via member variables! _counter++; }
@Test public void doTest() throws SchedulerException, MeasurementException { PollJob job = new PollJob(); JobExecutionContext context = mock(JobExecutionContext.class); Map params = new HashMap(); JobDataMap jobMap = new JobDataMap(params); MeasurementDefinition def = MocksFactory.createMockMeasurementDefinition(); MeasurementListener listener = mock(MeasurementListener.class); Scheduler scheduler = mock(Scheduler.class); CoreMeasurementService service = mock(CoreMeasurementService.class); SchedulerContext schedulerContext = new SchedulerContext( Collections.singletonMap(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service)); jobMap.put(PollJob.LISTENER_ATTR_NAME, listener); jobMap.put(PollJob.MEASUREMENT_DEF_ATTR_NAME, def); jobMap.put(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service); when(context.getMergedJobDataMap()).thenReturn(jobMap); when(context.getScheduler()).thenReturn(scheduler); when(scheduler.getContext()).thenReturn(schedulerContext); CapabilityValue capValue = new CapabilityValue(RandomUtils.nextLong()); when(service.getCapabilityValue(Matchers.<String>any(), Matchers.<String>any())) .thenReturn(capValue); job.execute(context); verify(context).getMergedJobDataMap(); verify(service).getCapabilityValue(def.getResourceUri(), def.getCapabilityUri()); verify(listener).newCapabilityValue(capValue); assertEquals(capValue.getMetricsId(), def.getId()); }
/** * Execute the job. Called by the <code>{@link org.quartz.Scheduler}</code> when a <code> * {@link org.quartz.Trigger}</code> fires that is associated with the <code>Job</code>. * * @throws JobExecutionException if there is an exception while executing the job. */ public void execute(JobExecutionContext context) throws JobExecutionException { try { String instName = context.getJobDetail().getName(); String instGroup = context.getJobDetail().getGroup(); JobDataMap dataMap = context.getJobDetail().getJobDataMap(); // String jobSays = dataMap.getString("jobSays"); // float myFloatValue = dataMap.getFloat("myFloatValue"); // test_name and hostname should extracted from context String application = dataMap.getString("application"); String hostname = dataMap.getString("hostname"); // System.err.println("Instance " + instName + " of DumbJob says: " + jobSays); // Call Submition API SmartfrogAdapter sfAdap = new SmartFrogAdapterImpl("D:\\cvs\\forge\\2006\\aug21\\core\\smartfrog\\dist", false); Map cd1 = sfAdap.submit(application, null, new String[] {hostname}); // Say Hello to the World and display the date/time log.info("Hello World! - " + new Date()); log.info("Submission Done " + cd1.toString()); } catch (Exception ex) { log.error(ex); } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { Task task = (Task) context.getJobDetail().getJobDataMap().get(QuartzShedulerManager.TASK); task.execute( (Map<String, Object>) context.getJobDetail().getJobDataMap().get(QuartzShedulerManager.TASK_PARAM)); }
/** Ejecución del trabajo lanzar RSS */ public void execute(JobExecutionContext context) throws JobExecutionException { String usuario = (String) context.getJobDetail().getJobDataMap().get(CtesPlanificador.USUARIO); /* Añadimos la seguridad al proceso */ log("Usuario que lanza la tarea: " + usuario); boolean contextoCargado = Autenticar.cargarContextoSeguridad(usuario); if (!contextoCargado) { log.error("ERROR: No han cargado los datos en el contexto de seguridad"); return; } log( "Informes portada: " + context.getJobDetail().getFullName() + " ejecutandose a las " + new Date()); try { SrvPlanificadorService servicio = ServiceLocator.instance().getSrvPlanificadorService(); servicio.informesPortada(); log("Se han generado los informes de portada"); } catch (Exception e) { JobExecutionException excepcion = new JobExecutionException("Error: No se ha podido realizar los Informes de portada ", e); log.error("Error " + excepcion); /* Se lanza el error */ throw excepcion; } }
public void execute(JobExecutionContext exeInfo) throws JobExecutionException { System.out.println("IN execute job warning"); System.out.println("auction ID: " + exeInfo.getJobDetail().getJobDataMap().getInt("auctionId")); MailSender.sendAuctionWarningMailToOwner( exeInfo.getJobDetail().getJobDataMap().getString("mail"), exeInfo.getJobDetail().getJobDataMap().getString("bookName"), exeInfo.getJobDetail().getJobDataMap().getString("personName")); }
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap(); String receiverKey = (String) map.get(QuartzMessageReceiver.QUARTZ_RECEIVER_PROPERTY); if (receiverKey == null) throw new JobExecutionException(QuartzMessages.receiverNotInJobDataMap().getMessage()); String connectorName = (String) map.get(QuartzMessageReceiver.QUARTZ_CONNECTOR_PROPERTY); if (connectorName == null) throw new JobExecutionException(QuartzMessages.connectorNotInJobDataMap().getMessage()); AbstractConnector connector = (AbstractConnector) RegistryContext.getRegistry().lookupConnector(connectorName); if (connector == null) throw new JobExecutionException(QuartzMessages.noConnectorFound(connectorName).getMessage()); AbstractMessageReceiver receiver = (AbstractMessageReceiver) connector.lookupReceiver(receiverKey); if (receiver == null) throw new JobExecutionException( QuartzMessages.noReceiverInConnector(receiverKey, connectorName).getMessage()); Object payload = jobExecutionContext.getJobDetail().getJobDataMap().get(QuartzConnector.PROPERTY_PAYLOAD); try { if (payload == null) { String ref = jobExecutionContext .getJobDetail() .getJobDataMap() .getString(QuartzConnector.PROPERTY_PAYLOAD_REFERENCE); // for backward compatibility check the old payload Class property // too if (ref == null) { ref = jobExecutionContext .getJobDetail() .getJobDataMap() .getString(QuartzConnector.PROPERTY_PAYLOAD_CLASS_NAME); } if (ref == null) { payload = NullPayload.getInstance(); } else { payload = RegistryContext.getRegistry().lookupObject(ref); } if (payload == null) { logger.warn("There is no payload attached to this quartz job. Sending Null payload"); payload = NullPayload.getInstance(); } } receiver.routeMessage(new MuleMessage(receiver.getConnector().getMessageAdapter(payload))); } catch (Exception e) { receiver.handleException(e); } }
@Override public void execute(final JobExecutionContext jobCtx) throws JobExecutionException { jobKeys.add(jobCtx.getJobDetail().getKey().getName()); triggerKeys.add(jobCtx.getTrigger().getKey().getName()); count++; System.out.println( "Processing Trigger " + jobCtx.getTrigger().getKey().getName() + " " + new Date()); }
/** * Called by the <code>{@link Scheduler}</code> after a <code>{@link org.quartz.JobDetail}</code> * has been executed, and be for the associated <code>Trigger</code>'s <code>triggered(xx)</code> * method has been called. */ public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { if (jobException != null) { // 记录错误 SchedulerUtil.addErrorJob(context.getTrigger().getName(), jobException); logger.error(jobException); reportEmail(context, jobException); } else { SchedulerUtil.removeErrorJob(context.getTrigger().getName()); } }
@Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { logger.debug("Inicio del job para la comprobación del time-out en los envíos"); try { ServicioEntidades servicio = LocalizadorServicios.getServicioEntidades(); // Procesar los ficheros List<Entidad> listaEntidades = servicio.obtenerEntidades(); logger.debug("Numero Entidades recuperadas:" + listaEntidades.size()); for (Iterator iterator = listaEntidades.iterator(); iterator.hasNext(); ) { Entidad entidad = (Entidad) iterator.next(); try { entidad.getCodigoINE(); logger.debug("entdidad:" + entidad.getIdentificador()); MultiEntityContextHolder.setEntity(entidad.getIdentificador()); getServicioIntercambioRegistral().comprobarTimeOutEnvios(); context.setResult("Ok"); } catch (Throwable e) { logger.error( "Error al lanzar la comprobación del time-out en los envíos para la entidad:" + entidad.getIdentificador(), e); context.setResult( "Error al lanzar la comprobación del time-out en los envíos para la entidad:" + entidad.getIdentificador() + e.toString()); throw new JobExecutionException( "Error al lanzar la comprobación del time-out en los envíospara la entidad:" + entidad.getIdentificador(), e); } finally { logger.info( "Fin del job para la comprobación del time-out en los envíos para la entidad:" + entidad.getIdentificador()); } } } catch (Throwable e) { logger.error("Error al lanzar la comprobación del time-out en los envíos", e); context.setResult( "Error al lanzar la comprobación del time-out en los envíos: " + e.toString()); throw new JobExecutionException( "Error al lanzar la comprobación del time-out en los envíos", e); } finally { logger.info("Fin del job para la comprobación del time-out en los envíos"); } }
/** 停止作业. */ public void stopJob() { try { for (JobExecutionContext each : scheduler.getCurrentlyExecutingJobs()) { if (each.getJobInstance() instanceof AbstractElasticJob) { ((AbstractElasticJob) each.getJobInstance()).stop(); } } scheduler.pauseAll(); } catch (final SchedulerException ex) { throw new JobException(ex); } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { Synchronizer runObject = (Synchronizer) context.getJobDetail().getJobDataMap().get(JobDataMapKey.RUN_OBJECT); try { String currentAppName = (String) context.getJobDetail().getJobDataMap().get(JobDataMapKey.RUN_MAGIC); /*EagleEye.startTrace(EagleEye.generateTraceId(null), "time://" + currentAppName + "/" + getName() + "Synchronizer");*/ runObject.sync(); } finally { /*EagleEye.endTrace();*/ } }
/** @see org.quartz.Job#execute(org.quartz.JobExecutionContext) */ public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap mergedJobDataMap = context.getMergedJobDataMap(); SchedulerContext schedCtxt = null; try { schedCtxt = context.getScheduler().getContext(); } catch (SchedulerException e) { throw new JobExecutionException("Error obtaining scheduler context.", e, false); } String fileName = mergedJobDataMap.getString(FILE_NAME); String listenerName = mergedJobDataMap.getString(FILE_SCAN_LISTENER_NAME); if (fileName == null) { throw new JobExecutionException( "Required parameter '" + FILE_NAME + "' not found in merged JobDataMap"); } if (listenerName == null) { throw new JobExecutionException( "Required parameter '" + FILE_SCAN_LISTENER_NAME + "' not found in merged JobDataMap"); } FileScanListener listener = (FileScanListener) schedCtxt.get(listenerName); if (listener == null) { throw new JobExecutionException( "FileScanListener named '" + listenerName + "' not found in SchedulerContext"); } long lastDate = -1; if (mergedJobDataMap.containsKey(LAST_MODIFIED_TIME)) { lastDate = mergedJobDataMap.getLong(LAST_MODIFIED_TIME); } long newDate = getLastModifiedDate(fileName); if (newDate < 0) { log.warn("File '" + fileName + "' does not exist."); return; } if (lastDate > 0 && (newDate != lastDate)) { // notify call back... log.info("File '" + fileName + "' updated, notifying listener."); listener.fileUpdated(fileName); } else if (log.isDebugEnabled()) { log.debug("File '" + fileName + "' unchanged."); } // It is the JobDataMap on the JobDetail which is actually stateful context.getJobDetail().getJobDataMap().put(LAST_MODIFIED_TIME, newDate); }
/** @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext, JobExecutionException) */ public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { Trigger trigger = context.getTrigger(); Object[] args = null; Object oResult = context.getResult(); String result = showJobDataMap(oResult); if (jobException != null) { String errMsg = jobException.getMessage(); args = new Object[] { context.getJobDetail().getKey().getName(), context.getJobDetail().getKey().getGroup(), new java.util.Date(), trigger.getKey().getName(), trigger.getKey().getGroup(), trigger.getPreviousFireTime(), trigger.getNextFireTime(), Integer.valueOf(context.getRefireCount()), context.getFireInstanceId(), result, errMsg }; try { insertJobDetail(this.getNonManagedTXConnection(), context); getLog().info(MessageFormat.format(getJobFailedMessage(), args)); // without exception trace // getLog().info(MessageFormat.format(getJobFailedMessage(), args), // jobException); } catch (Exception e) { getLog().error(MessageFormat.format(getJobFailedMessage(), args, e)); } } else { args = new Object[] { context.getJobDetail().getKey().getName(), context.getJobDetail().getKey().getGroup(), new java.util.Date(), trigger.getKey().getName(), trigger.getKey().getGroup(), trigger.getPreviousFireTime(), trigger.getNextFireTime(), Integer.valueOf(context.getRefireCount()), context.getFireInstanceId(), result }; try { insertJobDetail(this.getNonManagedTXConnection(), context); getLog().info(MessageFormat.format(getJobSuccessMessage(), args)); } catch (Exception e) { getLog().error(MessageFormat.format(getJobSuccessMessage(), args, e)); } } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { String productId = context.getMergedJobDataMap().getString(JobStatus.TARGET_ID); Boolean lazy = context.getMergedJobDataMap().getBoolean(LAZY_REGEN); List<String> l = new ArrayList<String>(); l.add(productId); Set<Owner> owners = subAdapter.lookupOwnersByProduct(l); for (Owner owner : owners) { poolManager.refreshPools(owner, lazy); } context.setResult("Pools refreshed for product " + productId); }
protected void executeInternal(JobExecutionContext context) throws JobExecutionException { try { SchedulerContext schCtx = context.getScheduler().getContext(); JobDataMap jdm = context.getJobDetail().getJobDataMap(); // 获取采集源 this.acquId = Integer.parseInt((String) jdm.get(CmsTask.TASK_PARAM_ACQU_ID)); // 获取Spring中的上下文 ApplicationContext appCtx = (ApplicationContext) schCtx.get("applicationContext"); this.acquisitionSvc = (AcquisitionSvc) appCtx.getBean("acquisitionSvc"); } catch (SchedulerException e1) { // TODO 尚未处理异常 e1.printStackTrace(); } acquStart(); }
public void execute(JobExecutionContext context) throws JobExecutionException { try { @SuppressWarnings("unchecked") List<Long> jobExecTimestamps = (List<Long>) context.getScheduler().getContext().get(DATE_STAMPS); CyclicBarrier barrier = (CyclicBarrier) context.getScheduler().getContext().get(BARRIER); jobExecTimestamps.add(System.currentTimeMillis()); barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (Throwable e) { e.printStackTrace(); throw new AssertionError("Await on barrier was interrupted: " + e.toString()); } }
/** 提醒操作 */ @Override public void execute(JobExecutionContext context) throws JobExecutionException { SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 获取添加任务时的参数(时间) JobDataMap data = context.getJobDetail().getJobDataMap(); Long time = data.getLong("time"); List<Remind> reminds = new RemindService().loadByTime(time); // 数据库读取time时刻提醒 for (int i = 0; i < reminds.size(); i++) { // 执行post请求微信服务器 int id = reminds.get(i).getId(); String response = Util.loadJSON("http://ly.linteng.wang/xs/home/index/send?key=wanglinteng&id=" + id); try { Util.SendLog( " 执行时间为:" + dateformat.format(new Date(time * 1000)) + " 的定时任务,提醒ID为:【" + id + "】,返回值:" + response); } catch (IOException e) { e.printStackTrace(); } } Quartz.removeJob(time); // 执行完立即移除自己的触发器 }
/** * 发送email,报告错误 * * @param context * @param jobEx */ private void reportEmail(JobExecutionContext context, JobExecutionException jobEx) { ConfigUtil configUtil = ConfigUtil.getInstance(); MailEngine mailEngine = (MailEngine) ContextUtil.getSpringBeanById("mailEngine"); if (mailEngine == null) { return; } String error = new StringBuilder("Trigger[") .append(context.getTrigger().getName()) .append("]<br/> Time[") .append(new Date()) .append("]<br/><br/>StoreURL:") .append(ConfigUtil.getInstance().getStore().getSiteUrl()) .append("<br/><br/>") .append(jobEx.toString()) .toString(); Map model = new HashMap(); model.put("errorMsg", error); try { mailEngine.sendSimpleTemplateMail( EMAIL_TEMPLATE, model, null, null, configUtil.getBugReportEmail()); } catch (Exception e) { logger.error(e); } }
/** * Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>{@link org.quartz.Trigger} * </code> fires that is associated with the <code>Job</code>. * * @throws JobExecutionException if there is an exception while executing the job. */ public void execute(JobExecutionContext context) throws JobExecutionException { _jobKey = context.getJobDetail().getKey(); _log.info("---- " + _jobKey + " executing at " + new Date()); try { // main job loop... see the JavaDOC for InterruptableJob for discussion... // do some work... in this example we are 'simulating' work by sleeping... :) for (int i = 0; i < 4; i++) { try { Thread.sleep(1000L); } catch (Exception ignore) { ignore.printStackTrace(); } // periodically check if we've been interrupted... if (_interrupted) { _log.info("--- " + _jobKey + " -- Interrupted... bailing out!"); return; // could also choose to throw a JobExecutionException // if that made for sense based on the particular // job's responsibilities/behaviors } } } finally { _log.info("---- " + _jobKey + " completed at " + new Date()); } }
@SuppressWarnings("unchecked") @Override public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap dataMap = context.getJobDetail().getJobDataMap(); // 取得所传递的参数 Map<String, Object> paramMap = (Map<String, Object>) dataMap.get("jobParams"); SeqLinkedList seqParam = new SeqLinkedList(); // 放入job参数信息 if (null != paramMap) { Iterator<Entry<String, Object>> iter = paramMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Object> entry = iter.next(); seqParam.putParam(entry.getKey(), entry.getValue()); } } // 将所有代码流程添加到容器中 seqParam.addExec(jobExecuteFlow); boolean exec = false; try { exec = seqParam.nextExec(); } catch (Exception e) { e.printStackTrace(); } // 释放内存 seqParam = null; System.out.println(exec); }