下面列出了怎么用org.quartz.SchedulerContext的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void execute(JobExecutionContext jobExecutionContext) {
try {
SchedulerContext schedulerContext = jobExecutionContext.getScheduler().getContext();
PushSource.Context pushSourceContext = (PushSource.Context) schedulerContext.get(
SchedulerPushSource.PUSH_SOURCE_CONTEXT
);
if (pushSourceContext != null) {
BatchContext batchContext = pushSourceContext.startBatch();
Record record = pushSourceContext.createRecord("cronRecord");
LinkedHashMap<String, Field> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("timestamp", Field.createDatetime(new Date()));
record.set(Field.createListMap(linkedHashMap));
batchContext.getBatchMaker().addRecord(record);
pushSourceContext.processBatch(batchContext);
}
} catch (SchedulerException ex) {
LOG.error(ex.getMessage(), ex);
}
}
/**
* {@inheritDoc}
*
* @param context
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
this.context = context;
SchedulerContext schedulerContext = null;
try {
log.debug("Executing quartz job");
schedulerContext = context.getScheduler().getContext();
initProperties(schedulerContext);
WebResource.Builder resourceBuilder = getBuilder();
ClientResponse response = getResponse(resourceBuilder);
if (response != null) {
String responseAsString = response.getEntity(String.class);
final List<Event> events = restSourceHandler
.getEvents(responseAsString, responseToHeaders(response.getHeaders()));
queue.addAll(events);
urlHandler.updateFilterParameters(getLastEvent(events));
}
} catch (Exception e) {
log.error("Error getting Response: " + e.getMessage());
}
}
protected void executeInternal(JobExecutionContext context)throws JobExecutionException {
try {
SchedulerContext schCtx = context.getScheduler().getContext();
JobDataMap jdm=context.getJobDetail().getJobDataMap();
//获取Spring中的上下文
ApplicationContext appCtx = (ApplicationContext)schCtx.get("applicationContext");
this.cmsSiteMng= (CmsSiteMng)appCtx.getBean("cmsSiteMng");
this.staticPageSvc= (StaticPageSvc)appCtx.getBean("staticPageSvc");
this.sessionFactory=(SessionFactory) appCtx.getBean("sessionFactory");
this.siteId=Integer.parseInt((String) jdm.get(CmsTask.TASK_PARAM_SITE_ID));
} catch (SchedulerException e1) {
// TODO 尚未处理异常
e1.printStackTrace();
}
staticIndex();
}
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();
}
@Test
public void schedulerFactoryBeanWithApplicationContext() throws Exception {
TestBean tb = new TestBean("tb", 99);
StaticApplicationContext ac = new StaticApplicationContext();
final Scheduler scheduler = mock(Scheduler.class);
SchedulerContext schedulerContext = new SchedulerContext();
given(scheduler.getContext()).willReturn(schedulerContext);
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) {
return scheduler;
}
};
schedulerFactoryBean.setJobFactory(null);
Map<String, Object> schedulerContextMap = new HashMap<>();
schedulerContextMap.put("testBean", tb);
schedulerFactoryBean.setSchedulerContextAsMap(schedulerContextMap);
schedulerFactoryBean.setApplicationContext(ac);
schedulerFactoryBean.setApplicationContextSchedulerContextKey("appCtx");
try {
schedulerFactoryBean.afterPropertiesSet();
schedulerFactoryBean.start();
Scheduler returnedScheduler = schedulerFactoryBean.getObject();
assertEquals(tb, returnedScheduler.getContext().get("testBean"));
assertEquals(ac, returnedScheduler.getContext().get("appCtx"));
}
finally {
schedulerFactoryBean.destroy();
}
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
@Test
public void schedulerFactoryBeanWithApplicationContext() throws Exception {
TestBean tb = new TestBean("tb", 99);
StaticApplicationContext ac = new StaticApplicationContext();
final Scheduler scheduler = mock(Scheduler.class);
SchedulerContext schedulerContext = new SchedulerContext();
given(scheduler.getContext()).willReturn(schedulerContext);
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) {
return scheduler;
}
};
schedulerFactoryBean.setJobFactory(null);
Map<String, Object> schedulerContextMap = new HashMap<>();
schedulerContextMap.put("testBean", tb);
schedulerFactoryBean.setSchedulerContextAsMap(schedulerContextMap);
schedulerFactoryBean.setApplicationContext(ac);
schedulerFactoryBean.setApplicationContextSchedulerContextKey("appCtx");
try {
schedulerFactoryBean.afterPropertiesSet();
schedulerFactoryBean.start();
Scheduler returnedScheduler = schedulerFactoryBean.getObject();
assertEquals(tb, returnedScheduler.getContext().get("testBean"));
assertEquals(ac, returnedScheduler.getContext().get("appCtx"));
}
finally {
schedulerFactoryBean.destroy();
}
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
protected Object getService(JobExecutionContext context, String serviceName) throws JobExecutionException {
try {
SchedulerContext sc = context.getScheduler().getContext();
ApplicationContext cxt = (ApplicationContext) sc.get(MonitoringJob.CONTEXT_NAME);
return cxt.getBean(serviceName);
} catch (SchedulerException e) {
throw new JobExecutionException("Failed look up the " + serviceName + " " + e.toString());
}
}
/**
* <p>
* Returns the <code>SchedulerContext</code> of the <code>Scheduler</code>.
* </p>
*/
public SchedulerContext getContext() throws SchedulerException {
try {
return getRemoteScheduler().getSchedulerContext();
} catch (RemoteException re) {
throw invalidateHandleCreateException(
"Error communicating with remote scheduler.", re);
}
}
/**
* <p>
* Returns the <code>SchedulerContext</code> of the <code>Scheduler</code>.
* </p>
*/
public SchedulerContext getContext() throws SchedulerException {
try {
return getRemoteScheduler().getSchedulerContext();
} catch (RemoteException re) {
throw invalidateHandleCreateException(
"Error communicating with remote scheduler.", re);
}
}
/**
* 初始化自动的调度器数据
*
* @param scheduler 调度器
* @param jobBeanFactory JobBean工厂
*/
static void initAutomaticScheduler(Scheduler scheduler, JobBeanFactory jobBeanFactory) {
try {
SchedulerContext schedulerContext = scheduler.getContext();
schedulerContext.put(JOB_BEAN_FACTORY_KEY, jobBeanFactory);
schedulerContext.put(SCHEDULE_MODE_KEY, ScheduleMode.AUTOMATIC);
} catch (SchedulerException e) {
LoggerHelper.error("get schedule context failed.", e);
throw new NiubiException(e);
}
}
/**
* 初始化手动的调度器数据
*
* @param scheduler 调度器
*/
static void initManualScheduler(Scheduler scheduler) {
try {
SchedulerContext schedulerContext = scheduler.getContext();
schedulerContext.put(SCHEDULE_MODE_KEY, ScheduleMode.MANUAL);
} catch (SchedulerException e) {
LoggerHelper.error("get schedule context failed.", e);
throw new NiubiException(e);
}
}
@Test
public void schedulerFactoryBeanWithApplicationContext() throws Exception {
TestBean tb = new TestBean("tb", 99);
StaticApplicationContext ac = new StaticApplicationContext();
final Scheduler scheduler = mock(Scheduler.class);
SchedulerContext schedulerContext = new SchedulerContext();
given(scheduler.getContext()).willReturn(schedulerContext);
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) {
return scheduler;
}
};
schedulerFactoryBean.setJobFactory(null);
Map<String, Object> schedulerContextMap = new HashMap<String, Object>();
schedulerContextMap.put("testBean", tb);
schedulerFactoryBean.setSchedulerContextAsMap(schedulerContextMap);
schedulerFactoryBean.setApplicationContext(ac);
schedulerFactoryBean.setApplicationContextSchedulerContextKey("appCtx");
try {
schedulerFactoryBean.afterPropertiesSet();
schedulerFactoryBean.start();
Scheduler returnedScheduler = schedulerFactoryBean.getObject();
assertEquals(tb, returnedScheduler.getContext().get("testBean"));
assertEquals(ac, returnedScheduler.getContext().get("appCtx"));
}
finally {
schedulerFactoryBean.destroy();
}
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
@Override
public void action(JobExecutionContext context) {
try {
long start = System.currentTimeMillis();
SchedulerContext schedulerContext = context.getScheduler().getContext();
ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);
// 应用相关
InspectHandler inspectHandler;
JobDataMap jobDataMap = context.getMergedJobDataMap();
String inspectorType = MapUtils.getString(jobDataMap, "inspectorType");
if (StringUtils.isBlank(inspectorType)) {
logger.error("=====================InspectorJob:inspectorType is null=====================");
return;
} else if (inspectorType.equals("host")) {
inspectHandler = applicationContext.getBean("hostInspectHandler", InspectHandler.class);
} else if (inspectorType.equals("app")) {
inspectHandler = applicationContext.getBean("appInspectHandler", InspectHandler.class);
} else {
logger.error("=====================InspectorJob:inspectorType not match:{}=====================", inspectorType);
return;
}
inspectHandler.handle();
long end = System.currentTimeMillis();
logger.info("=====================InspectorJob {} Done! cost={} ms=====================",
inspectHandler.getClass().getSimpleName(), (end - start));
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
@Override
public void action(JobExecutionContext context) {
try {
SchedulerContext schedulerContext = context.getScheduler().getContext();
ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);
ConfigService configService = applicationContext.getBean("configService", ConfigService.class);
configService.reloadSystemConfig();
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void action(JobExecutionContext context) {
try {
JobDataMap dataMap = context.getMergedJobDataMap();
String ip = dataMap.getString(ConstUtils.HOST_KEY);
long hostId = dataMap.getLong(ConstUtils.HOST_ID_KEY);
SchedulerContext schedulerContext = context.getScheduler().getContext();
ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);
MachineCenter machineCenter = applicationContext.getBean("machineCenter", MachineCenter.class);
machineCenter.asyncMonitorMachineStats(hostId, ip);
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void action(JobExecutionContext context) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SchedulerContext schedulerContext;
try {
schedulerContext = context.getScheduler().getContext();
ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);
EmailComponent emailComponent = applicationContext.getBean("emailComponent", EmailComponent.class);
ErrorLoggerWatcherMBean errorLoggerWatcher = applicationContext.getBean("errorLoggerWatcher", ErrorLoggerWatcherMBean.class);
// if (errorLoggerWatcher.getTotalErrorCount() == 0L) {
// logger.warn("errorLoggerWatcher.totalErrorCount == 0 -o-");
// return;
// }
String title = "CacheCloud异常统计, 日期:" + dateFormat.format(date) + ";服务器:" + System.getProperty("local.ip") + ";总数:" + errorLoggerWatcher.getTotalErrorCount();
StringBuilder buffer = new StringBuilder();
buffer.append(title + ":<br/>");
for (Map.Entry<String, Long> entry : errorLoggerWatcher.getErrorInfos().entrySet()) {
Long num = entry.getValue();
if (num == 0L) {
continue;
}
String key = entry.getKey();
buffer.append(key + "=" + num + "<br/>");
}
emailComponent.sendMailToAdmin(title, buffer.toString());
//清理异常
errorLoggerWatcher.clear();
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void action(JobExecutionContext context) {
try {
long startTime = System.currentTimeMillis();
SchedulerContext schedulerContext = context.getScheduler().getContext();
ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);
InstanceAlertConfigService instanceAlertConfigService = applicationContext.getBean("instanceAlertConfigService", InstanceAlertConfigService.class);
instanceAlertConfigService.monitorLastMinuteAllInstanceInfo();
logger.info("InstanceAlertValueJob cost time {} ms", (System.currentTimeMillis() - startTime));
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void action(JobExecutionContext context) {
try {
SchedulerContext schedulerContext = context.getScheduler().getContext();
ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);
AppDailyDataCenter appDailyDataCenter = applicationContext.getBean("appDailyDataCenter", AppDailyDataCenter.class);
appDailyDataCenter.sendAppDailyEmail();
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
SchedulerContext schedulerContext = context.getScheduler().getContext();
schedulerContext.put(JOB_THREAD, Thread.currentThread());
CyclicBarrier barrier = (CyclicBarrier) schedulerContext.get(BARRIER);
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 {
try {
SchedulerContext schedulerContext = context.getScheduler().getContext();
SchedulerService service = (SchedulerService) schedulerContext.get( "schedulerService" );
Value toSend = Value.create();
toSend.getFirstChild( "jobName" ).setValue( context.getJobDetail().getKey().getName() );
toSend.getFirstChild( "groupName" ).setValue( context.getJobDetail().getKey().getGroup() );
service.sendMessage( CommMessage.createRequest( service.getOperationName(), "/", toSend ) );
} catch( SchedulerException ex ) {
Interpreter.getInstance().logSevere( ex );
}
}
/**
* Gets the job context holder.
*
* @param jobContext
* the job context
* @return the job context holder
*/
protected final JobContextHolder getJobContextHolder(final JobExecutionContext jobContext) {
final Scheduler scheduler = jobContext.getScheduler();
JobContextHolder bean = null;
try {
final SchedulerContext schedulerContext = scheduler.getContext();
final ApplicationContext appContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT);
bean = appContext.getBean(JobContextHolder.class);
} catch (final SchedulerException e) {
LOGGER.error("Failed to get JobContextHolder",e );
}
return bean;
}
/**
* Prepare context mock.
*
* @param jobContextMock the job context mock
* @return the application context
* @throws SchedulerException the scheduler exception
*/
protected ApplicationContext prepareContextMock(final JobExecutionContext jobContextMock) throws SchedulerException {
final Scheduler scheduler = Mockito.mock(Scheduler.class);
Mockito.when(jobContextMock.getScheduler()).thenReturn(scheduler);
final SchedulerContext schedulerContext = Mockito.mock(SchedulerContext.class);
Mockito.when(scheduler.getContext()).thenReturn(schedulerContext);
final ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
Mockito.when(schedulerContext.get(Mockito.any(String.class))).thenReturn(applicationContext);
return applicationContext;
}
@Before
public void prepare() throws Exception {
JobDataMap map = new JobDataMap( new HashMap<String,String> ());
map.put( RoboconfScheduler.APP_NAME, "app" );
map.put( RoboconfScheduler.JOB_NAME, "job" );
map.put( RoboconfScheduler.CMD_NAME, "cmd" );
JobDetail jobDetail = Mockito.mock( JobDetail.class );
Mockito.when( jobDetail.getJobDataMap()).thenReturn( map );
this.manager = Mockito.spy( new Manager());
this.manager.configurationMngr().setWorkingDirectory( this.folder.newFolder());
this.commandMngr = Mockito.mock( ICommandsMngr.class );
Mockito.when( this.manager.commandsMngr()).thenReturn( this.commandMngr );
this.context = Mockito.mock( JobExecutionContext.class );
Mockito.when( this.context.get( RoboconfScheduler.MANAGER )).thenReturn( this.manager );
Mockito.when( this.context.getJobDetail()).thenReturn( jobDetail );
Scheduler scheduler = Mockito.mock( Scheduler.class );
Mockito.when( this.context.getScheduler()).thenReturn( scheduler );
SchedulerContext schedulerCtx = Mockito.mock( SchedulerContext.class );
Mockito.when( scheduler.getContext()).thenReturn( schedulerCtx );
Mockito.when( schedulerCtx.get( RoboconfScheduler.MANAGER )).thenReturn( this.manager );
}
/**
* Initialize properties that are received in the {@code SchedulerContext}.
*
* @param context
*/
@SuppressWarnings("unchecked")
public void initProperties(SchedulerContext context) {
queue = (LinkedBlockingQueue<Event>) context.get("queue");
properties = (Map<String, String>) context.get("properties");
client = (Client) context.get("client");
restSourceHandler = (RestSourceHandler) context.get(HANDLER);
urlHandler = (UrlHandler) context.get(URL_HANDLER);
}
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();
}
staticContent();
}
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 SchedulerContext getContext() {
try {
return scheduler.getContext();
} catch (final SchedulerException e) {
throw new QuartzSchedulerException(e);
}
}
@Override
public void setSchedulerContext(SchedulerContext schedulerContext) {
this.schedulerContext = schedulerContext;
}
@Override
public void setSchedulerContext(SchedulerContext schedulerContext) {
this.schedulerContext = schedulerContext;
}
/**
* 获取Scheduler基本信息
*
* @return 返回基本信息的Map
* @throws SchedulerException 异常
*/
public static List<SchedulerInfo> getAllSchedulerInfo() throws SchedulerException {
List<SchedulerInfo> schedulerInfos = new ArrayList<SchedulerInfo>();
Collection<Scheduler> allSchedulers = quartzManager.getSchedulers();
for (Scheduler scheduler : allSchedulers) {
// 获取Job数量
List<JobDetail> allJobsOfScheduler = QuartzUtils.getAllJobsOfScheduler(scheduler);
int triggerCount = 0;
// 错误Trigger数量
int triggerErrorCount = 0;
// 堵塞Trigger数量
int triggerBlockedCount = 0;
// 暂停Trigger数量
int triggerPausedCount = 0;
for (JobDetail jobDetail : allJobsOfScheduler) {
List<? extends Trigger> triggersOfJob = QuartzUtils.getTriggersOfJob(jobDetail, scheduler);
for (Trigger trigger : triggersOfJob) {
triggerCount++;
boolean isError = QuartzUtils.isTriggerError(trigger, scheduler);
if (isError) {
triggerErrorCount++;
}
boolean isBlocked = QuartzUtils.isTriggerBlocked(trigger, scheduler);
if (isBlocked) {
triggerBlockedCount++;
}
boolean isPaused = QuartzUtils.isTriggerPaused(trigger, scheduler);
if (isPaused) {
triggerPausedCount++;
}
}
}
// schedulerConext中参数Map
List<Map<String, Object>> schedulerContextMapList = new ArrayList<Map<String, Object>>();
SchedulerContext context = scheduler.getContext();
Set<String> contextKeySet = context.keySet();
for (String contextKey : contextKeySet) {
Map<String, Object> contextMap = new LinkedHashMap<String, Object>();
Object contextKeyObj = context.get(contextKey);
// 是否支持json转换
boolean support = JSONWriter.support(contextKeyObj);
if (support) {
contextMap.put("key", contextKey);
contextMap.put("value", contextKeyObj);
} else {
contextMap.put("key", contextKey);
contextMap.put("value", contextKeyObj.toString());
}
schedulerContextMapList.add(contextMap);
}
SchedulerInfo schedulerInfo = new SchedulerInfo();
schedulerInfo.setSchedulerName(scheduler.getSchedulerName());
schedulerInfo.setShutdown(scheduler.isShutdown());
schedulerInfo.setStarted(scheduler.isStarted());
schedulerInfo.setInStandbyMode(scheduler.isInStandbyMode());
// 设置job数量
schedulerInfo.setJobCount(allJobsOfScheduler.size());
// 设置数量
schedulerInfo.setTriggerCount(triggerCount);
schedulerInfo.setTriggerErrorCount(triggerErrorCount);
schedulerInfo.setTriggerBlockedCount(triggerBlockedCount);
schedulerInfo.setTriggerPausedCount(triggerPausedCount);
// 设置schedulerContext
schedulerInfo.setSchedulerContext(schedulerContextMapList);
schedulerInfos.add(schedulerInfo);
}
return schedulerInfos;
}