下面列出了org.quartz.JobDataMap#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Execute the discoverer and the indexer.
*
* @param context
* @throws org.quartz.JobExecutionException
*/
@SuppressWarnings( "unchecked" )
@Override
public void execute( JobExecutionContext context )
throws JobExecutionException
{
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
setJobDataMap( dataMap );
TaskQueue taskQueue = (TaskQueue) dataMap.get( DefaultRepositoryArchivaTaskScheduler.TASK_QUEUE );
String repositoryId = (String) dataMap.get( DefaultRepositoryArchivaTaskScheduler.TASK_REPOSITORY );
RepositoryTask task = new RepositoryTask();
task.setRepositoryId( repositoryId );
try
{
taskQueue.put( task );
}
catch ( TaskQueueException e )
{
throw new JobExecutionException( e );
}
}
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDataMap jobData = context.getJobDetail().getJobDataMap();
UserUsageTrackingComponent usageComponent = (UserUsageTrackingComponent) jobData.get(KEY_COMPONENT);
if (usageComponent == null)
{
throw new JobExecutionException("Missing job data: " + KEY_COMPONENT);
}
// perform the content usage calculations
usageComponent.execute();
}
/**
* Calls the feed cleaner to do its work
*/
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDataMap jobData = context.getJobDetail().getJobDataMap();
// extract the feed cleaner to use
Object feedCleanerObj = jobData.get("feedCleaner");
if (feedCleanerObj == null || !(feedCleanerObj instanceof FeedCleaner))
{
throw new AlfrescoRuntimeException(
"FeedCleanupJob data must contain valid 'feedCleaner' reference");
}
FeedCleaner feedCleaner = (FeedCleaner)feedCleanerObj;
feedCleaner.execute();
}
@Override
public void execute(JobExecutionContext context) {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
Note note = (Note) jobDataMap.get("note");
LOGGER.info("Start cron job of note: " + note.getId());
if (note.haveRunningOrPendingParagraphs()) {
LOGGER.warn(
"execution of the cron job is skipped because there is a running or pending "
+ "paragraph (note id: {})",
note.getId());
return;
}
String cronExecutingUser = (String) note.getConfig().get("cronExecutingUser");
String cronExecutingRoles = (String) note.getConfig().get("cronExecutingRoles");
if (null == cronExecutingUser) {
cronExecutingUser = "anonymous";
}
AuthenticationInfo authenticationInfo =
new AuthenticationInfo(
cronExecutingUser,
StringUtils.isEmpty(cronExecutingRoles) ? null : cronExecutingRoles,
null);
try {
note.runAll(authenticationInfo, true, true, new HashMap<>());
} catch (Exception e) {
LOGGER.warn("Fail to run note: " + note.getName(), e);
}
}
/**
* Calls {@link FixedAclUpdater} to do it's work
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
Object fixedAclUpdaterObject = jobDataMap.get("fixedAclUpdater");
if (fixedAclUpdaterObject == null || !(fixedAclUpdaterObject instanceof FixedAclUpdater))
{
throw new AlfrescoRuntimeException("FixedAclUpdaterJob must contain a valid 'fixedAclUpdater'");
}
FixedAclUpdater fixedAclUpdater = (FixedAclUpdater)fixedAclUpdaterObject;
fixedAclUpdater.execute();
}
@SuppressWarnings("unchecked")
@Override
public void execute(JobExecutionContext ctx) throws JobExecutionException {
/* if task execution node is not fully started yet, ignore this trigger */
if (!TasksDSComponent.getTaskService().isServerInit()) {
if (log.isDebugEnabled()) {
log.debug("Ignoring task triggered before server startup: " + ctx.getJobDetail());
}
return;
}
JobDataMap dataMap = ctx.getJobDetail().getJobDataMap();
String taskClassName = dataMap.getString(TaskConstants.TASK_CLASS_NAME);
if (taskClassName == null) {
throw new JobExecutionException("The task class is missing in the job data map");
}
try {
Task task = (Task) Class.forName(taskClassName).newInstance();
Map<String, String> properties = (Map<String, String>) dataMap
.get(TaskConstants.TASK_PROPERTIES);
task.setProperties(properties);
int tenantId = Integer.parseInt(properties.get(TaskInfo.TENANT_ID_PROP));
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
task.init();
task.execute();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
} catch (Throwable e) {
String msg = "Error in executing task: " + e.getMessage();
log.error(msg, e);
throw new JobExecutionException(msg, e);
}
}
static void taskInfoReport(JobDataMap jobDataMap, String executeState) {
DataPoint influxdbDataPoint = new DataPoint();
influxdbDataPoint.setDatabase(TaskMonitorDataReportUtils.TASK_DATABASE);
influxdbDataPoint.setBizTag(TaskMonitorDataReportUtils.TASK_DATABASE_TABLE);
Map<String, String> tags = new HashMap<>(8);
tags.put("serviceName", jobDataMap.getString("serviceName"));
tags.put("methodName", jobDataMap.getString("methodName"));
tags.put("versionName", jobDataMap.getString("versionName"));
tags.put("serverIp", jobDataMap.getString("serverIp"));
tags.put("serverPort", jobDataMap.getString("serverPort"));
tags.put("executeState", executeState);
influxdbDataPoint.setTags(tags);
Map<String, Long> fields = new HashMap<>(8);
LocalDateTime currentTime = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
LocalDateTime startTime = (LocalDateTime) jobDataMap.get("startTime");
long taskCost = Duration.between(startTime, currentTime).toMillis();
fields.put("costTime", taskCost);
influxdbDataPoint.setValues(fields);
influxdbDataPoint.setTimestamp(System.currentTimeMillis());
//放入上送列表
appendDataPoint(Lists.newArrayList(influxdbDataPoint));
}
@SuppressWarnings("unchecked")
private void sendEmail(JobDataMap map) {
String subject = map.getString("subject");
String messageBody = map.getString("messageBody");
List<String> to = (List<String>) map.get("to");
List<String> cc = (List<String>) map.get("cc");
List<String> bcc = (List<String>) map.get("bcc");
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, false);
for(String receipient : to) {
helper.setFrom("[email protected]", "Julius from Dynamic Quartz");
helper.setTo(receipient);
helper.setSubject(subject);
helper.setText(messageBody);
if(!isEmpty(cc))
helper.setCc(cc.stream().toArray(String[]::new));
if(!isEmpty(bcc))
helper.setBcc(bcc.stream().toArray(String[]::new));
mailSender.send(message);
}
} catch (MessagingException | UnsupportedEncodingException e) {
log.error("An error occurred: {}", e.getLocalizedMessage());
}
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
if (log.isDebugEnabled()) {
log.debug("Running Event Remover Job");
}
JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
CronWindowProcessor windowProcessor = (CronWindowProcessor) dataMap.get("windowProcessor");
windowProcessor.dispatchEvents();
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
long timestamp = System.currentTimeMillis() / 1000;
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
String pluginName = jobDataMap.getString("pluginName");
try {
SNMPV3Plugin plugin = (SNMPV3Plugin) jobDataMap.get("pluginObject");
List<SNMPV3UserInfo> jobUsers = (List<SNMPV3UserInfo>) jobDataMap.get("userInfoList");
MetricsCommon metricsValue = new SNMPV3MetricsValue(plugin,jobUsers,timestamp);
//SNMP监控数据获取时间较长,采用异步方式
ExecuteThreadUtil.execute(new JobThread(metricsValue,"snmp v3 job thread"));
} catch (Exception e) {
log.error("插件 {} 运行异常",pluginName,e);
}
}
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDataMap jobData = context.getJobDetail().getJobDataMap();
// extract the content Cleanup to use
Object nodeStringLengthWorkerObj = jobData.get(JOB_DATA_NODE_WORKER);
if (nodeStringLengthWorkerObj == null || !(nodeStringLengthWorkerObj instanceof NodeStringLengthWorker))
{
throw new AlfrescoRuntimeException(
"MaxStringLengthJob data '" + JOB_DATA_NODE_WORKER + "' must reference a " + NodeStringLengthWorker.class.getSimpleName());
}
NodeStringLengthWorker worker = (NodeStringLengthWorker) nodeStringLengthWorkerObj;
worker.execute();
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
long timestamp = System.currentTimeMillis() / 1000;
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
String pluginName = jobDataMap.getString("pluginName");
try {
DetectPlugin detectPlugin = (DetectPlugin) jobDataMap.get("pluginObject");
MetricsCommon metricsValue = new DetectMetricsValue(detectPlugin,timestamp);
//可能会涉及到外网的连接,采用异步方式
ExecuteThreadUtil.execute(new JobThread(metricsValue,"detect job thread"));
} catch (Exception e) {
log.error("插件 {} 运行异常",pluginName,e);
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
String pluginName = jobDataMap.getString("pluginName");
try {
JMXPlugin jmxPlugin = (JMXPlugin) jobDataMap.get("pluginObject");
String jmxServerName = jobDataMap.getString("jmxServerName");
List<JMXMetricsValueInfo> jmxMetricsValueInfos = JMXManager.getJmxMetricValue(jmxServerName,jmxPlugin);
//设置agentSignName
for (JMXMetricsValueInfo jmxMetricsValueInfo : jmxMetricsValueInfos) {
String agentSignName = jmxPlugin.agentSignName(jmxMetricsValueInfo,
jmxMetricsValueInfo.getJmxConnectionInfo().getPid());
if ("{jmxServerName}".equals(agentSignName)) {
//设置变量
jmxMetricsValueInfo.getJmxConnectionInfo().setName(jmxServerName);
}else{
jmxMetricsValueInfo.getJmxConnectionInfo().setName(agentSignName);
}
}
MetricsCommon jmxMetricsValue = new JMXMetricsValue(jmxPlugin,jmxMetricsValueInfos);
ReportMetrics.push(jmxMetricsValue.getReportObjects());
} catch (Exception e) {
log.error("插件 {} 运行异常",pluginName,e);
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
//
long time = System.currentTimeMillis();
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String timeStr = timeFormat.format(new Date(time));
String profileId = context.getJobDetail().getKey().getName();
String groupName = context.getJobDetail().getKey().getGroup();
log.debug("### Checking Time by schedule({}) :{}",profileId, timeStr);
SimpleTrigger st = (SimpleTrigger ) context.getTrigger();
int checkRate = (int)st.getRepeatInterval()/1000;
//ServiceProcessor 의 ProfileInjector 에 주기에 따라 profile Id 전송
// ProfileInjector profileInJector = new ProfileIntjector();
// profileInJector.sendProfile(profileId);
//JobDataMap dataMap = context.getMergedJobDataMap();
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
//JobDataMap dataMap = context.getTrigger().getJobDataMap();
ProfileForDB profileForDB = (ProfileForDB)dataMap.get("profile");
//log.debug("profileForDB.getPeriod()={}", profileForDB.getPeriod());
int period = profileForDB.getPeriod();
//int checkRate = dataMap.getInt("checkRate");
boolean happened = dataMap.getBoolean("happened"); //초기값=미발생
long lastTimeExecutedCm = dataMap.getLong("lastTimeExecutedCm"); //마지막 CM 발생 일시
//context.getJobDetail().getJobDataMap().put("lastTimeExecutedCm", lastTimeExecutedCm);
long currentTime = (new Date().getTime())/1000; //to sec
boolean result;
log.debug("## past={}, {} - {}", (currentTime - lastTimeExecutedCm), currentTime, lastTimeExecutedCm);
if (happened) { //이미 CM을 처리했으면
if (lastTimeExecutedCm==0 || (lastTimeExecutedCm + period) <= currentTime){ //시간이 경과 했으면
result = checkCm(profileId, CHECK_AND_RUN); //CM조사해서 발생했으면 실행후 발생(실행) 여부 리턴
lastTimeExecutedCm = currentTime; //마지막 실행시간 저장
dataMap.put("lastTimeExecutedCm", lastTimeExecutedCm);
} else {
result = checkCm(profileId, CHECK_ONLY); //CM조사해서발생여부만 리턴
}
if (result == false) {//발생하지 않으면
happened = false; // 실행 여부 초기화
dataMap.put("happened", happened);
}
} else { //CM이 실행하지 않았으면
result = checkCm(profileId, CHECK_AND_RUN); //CM실행후 발생(실행) 여부 리턴
if (result == true) {//처리되었으면
happened = true; // 실행했음
lastTimeExecutedCm = currentTime;
dataMap.put("happened", happened);
dataMap.put("lastTimeExecutedCm", lastTimeExecutedCm);
}
}
dataMap.put("lastTimeExecutedCm", lastTimeExecutedCm);
dataMap.put("profile", profileForDB);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String ctime = sdf.format(new Date());
log.debug("{} - result={}, happened={}, lastTimeExecutedCm={}\n", ctime, result, happened, lastTimeExecutedCm);
}
@Override
public void execute(final JobExecutionContext jobexecutioncontext) throws JobExecutionException
{
final JobDataMap dataMap = jobexecutioncontext.getJobDetail().getJobDataMap();
final HBBaseDataCollector collector = (HBBaseDataCollector) dataMap.get(COLLECTOR_KEY);
final HBDataSenderService hbDataSenderService = (HBDataSenderService) dataMap.get(DATA_SENDER_SERVICE_KEY);
final JobLockService jobLockService = (JobLockService) dataMap.get(JOB_LOCK_SERVICE_KEY);
ParameterCheck.mandatory(COLLECTOR_KEY, collector);
ParameterCheck.mandatory(DATA_SENDER_SERVICE_KEY, hbDataSenderService);
ParameterCheck.mandatory(JOB_LOCK_SERVICE_KEY, jobLockService);
QName lockQname = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, collector.getCollectorId());
LockCallback lockCallback = new LockCallback(lockQname);
try
{
// Get lock
String lockToken = jobLockService.getLock(lockQname, LOCK_TTL);
// Register the refresh callback which will keep the lock alive.
// The lock will not be released manually,
// instead the job lock service will check the callback (running) flag every LOCK_TTL/2 ms from lock acquisition
// and release the lock when the flag is set to false.
jobLockService.refreshLock(lockToken, lockQname, LOCK_TTL, lockCallback);
if (logger.isDebugEnabled())
{
logger.debug("Lock acquired: " + lockQname + ": " + lockToken);
}
// Collect data and pass it to the data sender service
collectAndSendDataLocked(collector, hbDataSenderService);
}
catch (LockAcquisitionException e)
{
if (logger.isDebugEnabled())
{
logger.debug("Skipping collect and send data (could not get lock): " + e.getMessage());
}
}
finally
{
if (logger.isDebugEnabled())
{
logger.debug("Finished collector job. ID: " + collector.getCollectorId());
}
lockCallback.running.set(false);
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
//
long time = System.currentTimeMillis();
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String timeStr = timeFormat.format(new Date(time));
String profileId = context.getJobDetail().getKey().getName();
String groupName = context.getJobDetail().getKey().getGroup();
log.debug("### Checking Time by schedule({}) :{}",profileId, timeStr);
SimpleTrigger st = (SimpleTrigger ) context.getTrigger();
int checkRate = (int)st.getRepeatInterval()/1000;
//ServiceProcessor 의 ProfileInjector 에 주기에 따라 profile Id 전송
// ProfileInjector profileInJector = new ProfileIntjector();
// profileInJector.sendProfile(profileId);
//JobDataMap dataMap = context.getMergedJobDataMap();
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
//JobDataMap dataMap = context.getTrigger().getJobDataMap();
ProfileForDB profileForDB = (ProfileForDB)dataMap.get("profile");
//log.debug("profileForDB.getPeriod()={}", profileForDB.getPeriod());
int period = profileForDB.getPeriod();
//int checkRate = dataMap.getInt("checkRate");
boolean happened = dataMap.getBoolean("happened"); //초기값=미발생
long lastTimeExecutedCm = dataMap.getLong("lastTimeExecutedCm"); //마지막 CM 발생 일시
//context.getJobDetail().getJobDataMap().put("lastTimeExecutedCm", lastTimeExecutedCm);
long currentTime = (new Date().getTime())/1000; //to sec
boolean result;
log.debug("## past={}, {} - {}", (currentTime - lastTimeExecutedCm), currentTime, lastTimeExecutedCm);
if (happened) { //이미 CM을 처리했으면
if (lastTimeExecutedCm==0 || (lastTimeExecutedCm + period) <= currentTime){ //시간이 경과 했으면
result = checkCm(profileId, CHECK_AND_RUN); //CM조사해서 발생했으면 실행후 발생(실행) 여부 리턴
lastTimeExecutedCm = currentTime; //마지막 실행시간 저장
dataMap.put("lastTimeExecutedCm", lastTimeExecutedCm);
} else {
result = checkCm(profileId, CHECK_ONLY); //CM조사해서발생여부만 리턴
}
if (result == false) {//발생하지 않으면
happened = false; // 실행 여부 초기화
dataMap.put("happened", happened);
}
} else { //CM이 실행하지 않았으면
result = checkCm(profileId, CHECK_AND_RUN); //CM실행후 발생(실행) 여부 리턴
if (result == true) {//처리되었으면
happened = true; // 실행했음
lastTimeExecutedCm = currentTime;
dataMap.put("happened", happened);
dataMap.put("lastTimeExecutedCm", lastTimeExecutedCm);
}
}
dataMap.put("lastTimeExecutedCm", lastTimeExecutedCm);
dataMap.put("profile", profileForDB);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String ctime = sdf.format(new Date());
log.debug("{} - result={}, happened={}, lastTimeExecutedCm={}\n", ctime, result, happened, lastTimeExecutedCm);
}
protected final Map<String, Object> getDriversData(JobDataMap mergedJobDataMap) {
return (Map<String, Object>) mergedJobDataMap.get(MAP_KEY_DRIVERS);
}
public void execute(JobExecutionContext context) throws JobExecutionException {
// get the reference to the Stick
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String serialPort = (String) dataMap.get("SerialPort");
OceanicValueSelector valueSelector = (OceanicValueSelector) dataMap.get("ValueSelector");
OceanicBinding theBinding = (OceanicBinding) dataMap.get("Binding");
theBinding.lockSerialDevices();
SerialDevice serialDevice = theBinding.serialDevices.get(serialPort);
String response = null;
if (serialDevice != null) {
response = serialDevice.requestResponse(valueSelector.name());
logger.debug("Requested '{}' from the oceanic unit, got '{}' back", valueSelector.name(), response);
}
theBinding.unlockSerialDevices();
// process response etc
if (response != null) {
for (OceanicBindingProvider provider : theBinding.providers) {
for (String itemName : provider.getItemNames()) {
String itemSerialPort = provider.getSerialPort(itemName);
OceanicValueSelector itemSelector = OceanicValueSelector
.getValueSelector(provider.getValueSelector(itemName), ValueSelectorType.GET);
if (itemSerialPort.equals(serialPort) && itemSelector.equals(valueSelector)) {
if (serialDevice.cachedValues.get(valueSelector) == null
|| !serialDevice.cachedValues.get(valueSelector).equals(response)) {
serialDevice.cachedValues.put(valueSelector, response);
State value;
try {
value = createStateForType(valueSelector, response);
} catch (BindingConfigParseException e) {
logger.error("An exception occurred while converting {} to a valid state : {}",
response, e.getMessage());
return;
}
serialDevice.eventPublisher.postUpdate(itemName, value);
}
}
}
}
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
Date startDate = new Date();
LOG.debug("methodInvokeJob start : " + DateUtils.formart(startDate));
long startTime = startDate.getTime();
JobDataMap jobDataMap = context.getMergedJobDataMap();
//Object methodInvokerObj = jobDataMap.get("methodInvoker");
Object jobClassObj = jobDataMap.get("jobClass");
Object constructorArgumentsObj = jobDataMap.get("constructorArguments");
Object jobClassMethodNameObj = jobDataMap.get("jobClassMethodName");
Object jobClassMethodArgsObj = jobDataMap.get("jobClassMethodArgs");
try {
String jobClass = (String) jobClassObj;
Object[] constructorArguments = (Object[]) constructorArgumentsObj;
String jobClassMethodName = (String) jobClassMethodNameObj;
Object[] jobClassMethodArgs = (Object[]) jobClassMethodArgsObj;
Object jobBean;
LOG.debug("methodInvokeJob jobClass:" + jobClass);
LOG.debug("methodInvokeJob jobClassMethodName:" + jobClassMethodName);
QuartzBeanManagerFacade quartzBeanManagerFacade = QuartzBeanManagerFacade.getInstance();
if (constructorArguments != null && constructorArguments.length > 0) {
jobBean = quartzBeanManagerFacade.getBean(jobClass, constructorArguments);
} else {
jobBean = quartzBeanManagerFacade.getBean(jobClass);
}
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetMethod(jobClassMethodName);
methodInvoker.setArguments(jobClassMethodArgs);
methodInvoker.setTargetObject(jobBean);
boolean prepared = methodInvoker.isPrepared();
if (!prepared) {
methodInvoker.prepare();
}
Object result = methodInvoker.invoke();
context.setResult(result);
Date endDate = new Date();
long endTime = endDate.getTime();
LOG.debug("methodInvokeJob end : " + DateUtils.formart(endDate) + "," + (endTime - startTime));
} catch (Exception e) {
LOG.error("MethodInvokeJob exception message:" + e.getMessage(), e);
e.printStackTrace();
throw new JobExecutionException(e);
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
SonosZonePlayer thePlayer = (SonosZonePlayer) dataMap.get("Player");
thePlayer.updateRunningAlarmProperties();
}