org.quartz.JobDataMap Java Examples

The following examples show how to use org.quartz.JobDataMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EmailService.java    From quartz-manager with MIT License 8 votes vote down vote up
public void updateJob(String group, String name, JobDescriptor descriptor) {
	try {
		JobDetail oldJobDetail = scheduler.getJobDetail(jobKey(name, group));
		if(Objects.nonNull(oldJobDetail)) {
			JobDataMap jobDataMap = oldJobDetail.getJobDataMap();
			jobDataMap.put("subject", descriptor.getSubject());
			jobDataMap.put("messageBody", descriptor.getMessageBody());
			jobDataMap.put("to", descriptor.getTo());
			jobDataMap.put("cc", descriptor.getCc());
			jobDataMap.put("bcc", descriptor.getBcc());
			JobBuilder jb = oldJobDetail.getJobBuilder();
			JobDetail newJobDetail = jb.usingJobData(jobDataMap).storeDurably().build();
			scheduler.addJob(newJobDetail, true);
			log.info("Updated job with key - {}", newJobDetail.getKey());
			return;
		}
		log.warn("Could not find job with key - {}.{} to update", group, name);
	} catch (SchedulerException e) {
		log.error("Could not find job with key - {}.{} to update due to error - {}", group, name, e.getLocalizedMessage());
	}
}
 
Example #2
Source File: JobUtil.java    From spring-boot-quartz-demo with MIT License 7 votes vote down vote up
/**
 * Create Quartz Job.
 * 
 * @param jobClass Class whose executeInternal() method needs to be called. 
 * @param isDurable Job needs to be persisted even after completion. if true, job will be persisted, not otherwise. 
 * @param context Spring application context.
 * @param jobName Job name.
 * @param jobGroup Job group.
 * 
 * @return JobDetail object
 */
protected static JobDetail createJob(Class<? extends QuartzJobBean> jobClass, boolean isDurable, 
		ApplicationContext context, String jobName, String jobGroup){
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(jobClass);
    factoryBean.setDurability(isDurable);
    factoryBean.setApplicationContext(context);
    factoryBean.setName(jobName);
    factoryBean.setGroup(jobGroup);
       
    // set job data map
       JobDataMap jobDataMap = new JobDataMap();
       jobDataMap.put("myKey", "myValue");
       factoryBean.setJobDataMap(jobDataMap);
       
       factoryBean.afterPropertiesSet();
       
    return factoryBean.getObject();
}
 
Example #3
Source File: HbaseResourceSensitivityPollingJob.java    From Eagle with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(JobExecutionContext context)
        throws JobExecutionException {
    JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
    try {
        List<HbaseResourceSensitivityAPIEntity>
        hbaseResourceSensitivity = load(jobDataMap, "HbaseResourceSensitivityService");
        if(hbaseResourceSensitivity == null) {
        	LOG.warn("Hbase resource sensitivity information is empty");
        	return;
        }
        Map<String, HbaseResourceSensitivityAPIEntity> map = Maps.uniqueIndex(
        		hbaseResourceSensitivity,
        		new Function<HbaseResourceSensitivityAPIEntity, String>() {
        			@Override
        			public String apply(HbaseResourceSensitivityAPIEntity input) {
        				return input.getTags().get("hbaseResource");
        			}
        		});
        ExternalDataCache.getInstance().setJobResult(getClass(), map);
    } catch(Exception ex) {
    	LOG.error("Fail to load hbase resource sensitivity data", ex);
    }
}
 
Example #4
Source File: WeatherJob.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void execute(JobExecutionContext jobContext) throws JobExecutionException {
    JobDataMap jobDataMap = jobContext.getJobDetail().getJobDataMap();

    String locationId = jobDataMap.getString("locationId");
    logger.debug("Starting Weather job for location '{}'", locationId);

    try {
        LocationConfig locationConfig = context.getConfig().getLocationConfig(locationId);
        WeatherProvider weatherProvider = WeatherProviderFactory
                .createWeatherProvider(locationConfig.getProviderName());
        context.setWeather(locationId, weatherProvider.getWeather(locationConfig));
        weatherPublisher.publish(locationId);

    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new JobExecutionException(ex.getMessage(), ex);
    }
}
 
Example #5
Source File: DelayedAsynchronousServiceCallProxy.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void scheduleMessage(PersistedMessageBO message) throws SchedulerException {
 LOG.debug("Scheduling execution of a delayed asynchronous message.");
 Scheduler scheduler = KSBServiceLocator.getScheduler();
 JobDataMap jobData = new JobDataMap();
 jobData.put(MessageServiceExecutorJob.MESSAGE_KEY, message);

    JobDetailImpl jobDetail = new JobDetailImpl("Delayed_Asynchronous_Call-" + Math.random(), "Delayed_Asynchronous_Call",
  MessageServiceExecutorJob.class);
 jobDetail.setJobDataMap(jobData);

    scheduler.getListenerManager().addJobListener( new MessageServiceExecutorJobListener());

    SimpleTriggerImpl trigger = new SimpleTriggerImpl("Delayed_Asynchronous_Call_Trigger-" + Math.random(),
  "Delayed_Asynchronous_Call", message.getQueueDate());

    trigger.setJobDataMap(jobData);// 1.6 bug required or derby will choke
 scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #6
Source File: EntityMocksHelper.java    From griffin with Apache License 2.0 6 votes vote down vote up
public static JobDetailImpl createJobDetail(
    String measureJson,
    String predicatesJson) {
    JobDetailImpl jobDetail = new JobDetailImpl();
    JobKey jobKey = new JobKey("name", "group");
    jobDetail.setKey(jobKey);
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put(MEASURE_KEY, measureJson);
    jobDataMap.put(PREDICATES_KEY, predicatesJson);
    jobDataMap.put(JOB_NAME, "jobName");
    jobDataMap.put("jobName", "jobName");
    jobDataMap.put(PREDICATE_JOB_NAME, "predicateJobName");
    jobDataMap.put(GRIFFIN_JOB_ID, 1L);
    jobDetail.setJobDataMap(jobDataMap);
    return jobDetail;
}
 
Example #7
Source File: ConfiguredJob.java    From iaf with Apache License 2.0 6 votes vote down vote up
public void execute(JobExecutionContext context) throws JobExecutionException {
	String ctName = Thread.currentThread().getName();
	try {
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		IbisManager ibisManager = (IbisManager)dataMap.get(MANAGER_KEY);
		JobDef jobDef = (JobDef)dataMap.get(JOBDEF_KEY);
		Thread.currentThread().setName(jobDef.getName() + "["+ctName+"]");
		log.info(getLogPrefix(jobDef) + "executing");
		jobDef.executeJob(ibisManager);
		log.debug(getLogPrefix(jobDef) + "completed");
	}
	catch (Exception e) {
		log.error(e);
		throw new JobExecutionException(e, false);
	}
	finally {
		Thread.currentThread().setName(ctName);
	}
}
 
Example #8
Source File: GobblinHelixJob.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public void executeImpl(JobExecutionContext context) throws JobExecutionException {
  JobDataMap dataMap = context.getJobDetail().getJobDataMap();
  final JobScheduler jobScheduler = (JobScheduler) dataMap.get(JobScheduler.JOB_SCHEDULER_KEY);
  // the properties may get mutated during job execution and the scheduler reuses it for the next round of scheduling,
  // so clone it
  final Properties jobProps = (Properties)((Properties) dataMap.get(JobScheduler.PROPERTIES_KEY)).clone();
  final JobListener jobListener = (JobListener) dataMap.get(JobScheduler.JOB_LISTENER_KEY);

  try {
    if (Boolean.valueOf(jobProps.getProperty(GobblinClusterConfigurationKeys.JOB_EXECUTE_IN_SCHEDULING_THREAD,
            Boolean.toString(GobblinClusterConfigurationKeys.JOB_EXECUTE_IN_SCHEDULING_THREAD_DEFAULT)))) {
      jobScheduler.runJob(jobProps, jobListener);
    } else {
      cancellable = jobScheduler.scheduleJobImmediately(jobProps, jobListener);
    }
  } catch (Throwable t) {
    throw new JobExecutionException(t);
  }
}
 
Example #9
Source File: RepositoryTaskJob.java    From archiva with Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    }
}
 
Example #10
Source File: FoxbpmJobExecutionContext.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
public FoxbpmJobExecutionContext(JobExecutionContext jobExecutionContext) {
	JobDataMap jobDataMap = jobExecutionContext.getJobDetail()
			.getJobDataMap();
	scheduleJob = jobExecutionContext.getJobInstance();
	this.tokenId = jobDataMap.getString(TOKEN_ID);
	this.processInstanceId = jobDataMap.getString(PROCESS_INSTANCE_ID);
	this.nodeId = jobDataMap.getString(NODE_ID);
	this.processKey = jobDataMap.getString(PROCESS_DEFINITION_KEY);
	this.processId = jobDataMap.getString(PROCESS_DEFINITION_ID);
	this.processName = jobDataMap.getString(PROCESS_DEFINITION_NAME);
	this.bizKey = jobDataMap.getString(BUSINESS_KEY);
	this.jobType = jobDataMap.getString("jobType");
	this.connectorId = jobDataMap.getString(CONNECTOR_ID);
	this.connectorInstanceId = jobDataMap.getString(CONNECTOR_INSTANCE_ID);
	this.connectorInstanceName = jobDataMap
			.getString(CONNECTOR_INSTANCE_NAME);
	this.eventType = jobDataMap.getString(EVENT_TYPE);
	this.eventName = jobDataMap.getString(EVENT_NAME);
	this.taskId = jobDataMap.getString(TASK_ID);

}
 
Example #11
Source File: FileSensitivityPollingJob.java    From Eagle with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(JobExecutionContext context)
		throws JobExecutionException {
	JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
	try{
		List<FileSensitivityAPIEntity> ipZones = load(jobDataMap);
		if(ipZones == null){
			LOG.warn("File sensitivity information is empty");
			return;
		}
		Map<String, FileSensitivityAPIEntity> map = Maps.uniqueIndex(ipZones, new Function<FileSensitivityAPIEntity, String>(){
			@Override
			public String apply(FileSensitivityAPIEntity input) {
				return input.getTags().get("filedir");
			}
		});
		ExternalDataCache.getInstance().setJobResult(getClass(), map);
	}catch(Exception ex){
		LOG.error("Fail loading file sensitivity data", ex);
	}
}
 
Example #12
Source File: IntervalJob.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void executeJob(JobDataMap jobDataMap) {
    Calendar now = Calendar.getInstance();

    // sun
    SunCalc sunCalc = new SunCalc();
    Sun sun = (Sun) context.getPlanet(PlanetName.SUN);
    sunCalc.setSunPosition(now, context.getConfig().getLatitude(), context.getConfig().getLongitude(), sun);
    planetPublisher.publish(PlanetName.SUN);

    // moon
    MoonCalc moonCalc = new MoonCalc();
    Moon moon = (Moon) context.getPlanet(PlanetName.MOON);
    moonCalc.setMoonPosition(now, context.getConfig().getLatitude(), context.getConfig().getLongitude(), moon);
    planetPublisher.publish(PlanetName.MOON);
}
 
Example #13
Source File: StdJDBCDelegate.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Remove the transient data from and then create a serialized <code>java.util.ByteArrayOutputStream</code>
 * version of a <code>{@link org.quartz.JobDataMap}</code>.
 * </p>
 * 
 * @param data
 *          the JobDataMap to serialize
 * @return the serialized ByteArrayOutputStream
 * @throws IOException
 *           if serialization causes an error
 */
protected ByteArrayOutputStream serializeJobData(JobDataMap data)
    throws IOException {
    if (canUseProperties()) {
        return serializeProperties(data);
    }

    try {
        return serializeObject(data);
    } catch (NotSerializableException e) {
        throw new NotSerializableException(
            "Unable to serialize JobDataMap for insertion into " + 
            "database because the value of property '" + 
            getKeyOfNonSerializableValue(data) + 
            "' is not serializable: " + e.getMessage());
    }
}
 
Example #14
Source File: ScheduleUtils.java    From ruoyiplus with MIT License 6 votes vote down vote up
/**
 * 立即执行任务
 */
public static int run(Scheduler scheduler, SysJob job)
{
    int rows = 0;
    try
    {
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, job);

        scheduler.triggerJob(getJobKey(job.getJobId()), dataMap);
        rows = 1;
    }
    catch (SchedulerException e)
    {
        log.error("run 异常:", e);
    }
    return rows;
}
 
Example #15
Source File: SchedulingPullActions.java    From syncope with Apache License 2.0 6 votes vote down vote up
protected <T extends Job> void schedule(final Class<T> reference, final Map<String, Object> jobMap)
        throws JobExecutionException {

    @SuppressWarnings("unchecked")
    T jobInstance = (T) ApplicationContextProvider.getBeanFactory().
            createBean(reference, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
    String jobName = getClass().getName() + SecureRandomUtils.generateRandomUUID();

    jobMap.put(JobManager.DOMAIN_KEY, AuthContextUtils.getDomain());

    ApplicationContextProvider.getBeanFactory().registerSingleton(jobName, jobInstance);

    JobBuilder jobDetailBuilder = JobBuilder.newJob(reference).
            withIdentity(jobName).
            usingJobData(new JobDataMap(jobMap));

    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger().
            withIdentity(JobNamer.getTriggerName(jobName)).
            startNow();

    try {
        scheduler.getScheduler().scheduleJob(jobDetailBuilder.build(), triggerBuilder.build());
    } catch (SchedulerException e) {
        throw new JobExecutionException("Could not schedule, aborting", e);
    }
}
 
Example #16
Source File: NodeCleanupJob.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void execute(JobExecutionContext context) throws JobExecutionException
{
    JobDataMap jobData = context.getJobDetail().getJobDataMap();
    // extract the content Cleanup to use
    Object nodeCleanupWorkerObj = jobData.get("nodeCleanupWorker");
    if (nodeCleanupWorkerObj == null || !(nodeCleanupWorkerObj instanceof NodeCleanupWorker))
    {
        throw new AlfrescoRuntimeException(
                "NodeCleanupJob data must contain valid 'nodeCleanupWorker' reference");
    }
    NodeCleanupWorker nodeCleanupWorker = (NodeCleanupWorker) nodeCleanupWorkerObj;
    List<String> cleanupLog = nodeCleanupWorker.doClean();
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug("Node cleanup log:");
        for (String log : cleanupLog)
        {
            logger.debug(log);
        }
    }
}
 
Example #17
Source File: ScriptExecution.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * helper function to create the timer
 *
 * @param instant the point in time when the code should be executed
 * @param closure string for job id
 * @param dataMap job data map, preconfigured with arguments
 * @return
 */
private static Timer makeTimer(AbstractInstant instant, String closure, JobDataMap dataMap) {

    Logger logger = LoggerFactory.getLogger(ScriptExecution.class);
    JobKey jobKey = new JobKey(instant.toString() + ": " + closure.toString());
    Trigger trigger = newTrigger().startAt(instant.toDate()).build();
    Timer timer = new TimerImpl(jobKey, trigger.getKey(), dataMap, instant);
    try {
        JobDetail job = newJob(TimerExecutionJob.class).withIdentity(jobKey).usingJobData(dataMap).build();
        if (TimerImpl.scheduler.checkExists(job.getKey())) {
            TimerImpl.scheduler.deleteJob(job.getKey());
            logger.debug("Deleted existing Job {}", job.getKey().toString());
        }
        TimerImpl.scheduler.scheduleJob(job, trigger);
        logger.debug("Scheduled code for execution at {}", instant.toString());
        return timer;
    } catch (SchedulerException e) {
        logger.error("Failed to schedule code for execution.", e);
        return null;
    }
}
 
Example #18
Source File: DataEnrichJob.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

    DataEnrichLCM lcm = (DataEnrichLCM)jobDataMap.getOrDefault("dataEnrichLCM", null);
    if(lcm == null)
        throw new IllegalStateException("dataEnrichLCM implementation should be provided");
    try {
        Collection externalEntities = lcm.loadExternal();
        Map<Object, Object> map = Maps.uniqueIndex(
                externalEntities,
                entity -> lcm.getCacheKey(entity)
            );
        ExternalDataCache.getInstance().setJobResult(lcm.getClass(), map);
    } catch(Exception ex) {
        LOG.error("Fail to load sensitivity data", ex);
    }
}
 
Example #19
Source File: TimerSchedulerController.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/insert")
public BaseRspEntity insertTimerScheduler(@Validated @RequestBody TimerScheduler timerScheduler) throws BrokerException {
    BaseRspEntity resEntity = new BaseRspEntity(ConstantsHelper.RET_SUCCESS);
    JobDataMap timerSchedulerMap = new JobDataMap();
    timerSchedulerMap.put("id", timerScheduler.getId());
    timerSchedulerMap.put("type", "createTimerTask");
    timerSchedulerMap.put("timer", JsonHelper.object2Json(timerScheduler));
    RetCode retCode = timerSchedulerService.createTimerScheduler(timerScheduler.getId(), "timer", "timer",
            "timer-trigger", TimerSchedulerJob.class, timerSchedulerMap, timerScheduler);
    if (ConstantsHelper.RET_FAIL.getErrorCode() == retCode.getErrorCode()) { //fail
        resEntity.setErrorCode(retCode.getErrorCode());
        resEntity.setErrorMsg(retCode.getErrorMsg());
    }

    return resEntity;
}
 
Example #20
Source File: ScheduledPersistedActionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected JobDetail buildJobDetail(ScheduledPersistedActionImpl schedule)
{
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put(JOB_ACTION_NODEREF, schedule.getActionNodeRef().toString());
    jobDataMap.put(JOB_SCHEDULE_NODEREF, schedule.getPersistedAtNodeRef().toString());
    return JobBuilder.newJob()
            .withIdentity(schedule.getPersistedAtNodeRef().toString(), SCHEDULER_GROUP)
            .ofType(ScheduledJobWrapper.class)
            .setJobData(jobDataMap)
            .build();
}
 
Example #21
Source File: SchedulerJobListener.java    From dapeng-soa with Apache License 2.0 5 votes vote down vote up
/**
 * (1)
 * 任务执行之前执行
 * Called by the Scheduler when a JobDetail is about to be executed (an associated Trigger has occurred).
 */
@Override
public void jobToBeExecuted(final JobExecutionContext context) {
    JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
    String serviceName = jobDataMap.getString("serviceName");
    String versionName = jobDataMap.getString("versionName");
    String methodName = jobDataMap.getString("methodName");

    context.getJobDetail().getJobDataMap().put("startTime", LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
    String message = String.format("SchedulerJobListener::jobToBeExecuted;Task[%s:%s:%s] 即将被执行", serviceName, versionName, methodName);
    //sendMessage(serviceName, versionName, methodName, message, false,"normal");
}
 
Example #22
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends AbstractJob> void scheduleLocal(Class<T> cls, Integer delay) throws Exception {
	/* 需要单独生成一个独立任务,保证group和预约的任务不重复 */
	JobDataMap jobDataMap = new JobDataMap();
	jobDataMap.put("context", this);
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.usingJobData(jobDataMap).withDescription(Config.node()).build();
	/* 经过测试0代表不重复,仅运行一次 */
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), clazz.getName())
			.withDescription("scheduleLocal").startAt(DateBuilder.futureDate(delay, IntervalUnit.SECOND))
			.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(0))
			.build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #23
Source File: JobService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private <T> JobDetail buildJobDetail(String sdxId, String crn, Class<? extends Job> clazz) {
    JobDataMap jobDataMap = new JobDataMap();

    jobDataMap.put(LOCAL_ID, sdxId);
    jobDataMap.put(REMOTE_RESOURCE_CRN, crn);

    return JobBuilder.newJob(clazz)
            .withIdentity(sdxId, JOB_GROUP)
            .withDescription("Checking datalake status Job")
            .usingJobData(jobDataMap)
            .storeDurably()
            .build();
}
 
Example #24
Source File: DistributeJob.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 
 * @param jdm
 * @return jdm中key参数(文件夹名称)
 */
@SuppressWarnings("unchecked")
private List<String> getFolderdKeys(JobDataMap jdm){
	List<String>keys=new ArrayList<String>();
	Set<String>keySet=jdm.keySet();
	Iterator<String>it=keySet.iterator();
	while(it.hasNext()){
		String key=it.next();
		if(key.startsWith(CmsTask.TASK_PARAM_FOLDER_PREFIX)){
			keys.add(key);
		}
	}
	return keys;
}
 
Example #25
Source File: ScheduleManager.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void scheduleJob(Scheduler sched, String name,
        int mode, long interval, Class task, JobDataMap data)
    throws SchedulerException {

    Trigger t = createTrigger(name, updateIndexGroupName, mode, interval);

    JobBuilder d = newJob(task).withIdentity(name, updateIndexGroupName);
    d.usingJobData(data);

    sched.scheduleJob(d.build(), t);
}
 
Example #26
Source File: DistributeJob.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 
 * @param jdm
 * @param key文件夹key
 * @return 文件夹
 */
private String getJobDataValue(JobDataMap jdm,String key){
	if(StringUtils.isBlank(key)){
		return null;
	}
	return (String) jdm.get(key);
}
 
Example #27
Source File: SimpleJob.java    From spring-boot-quartz-demo with MIT License 5 votes vote down vote up
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
	JobKey key = jobExecutionContext.getJobDetail().getKey();
	System.out.println("Simple Job started with key :" + key.getName() + ", Group :"+key.getGroup() + " , Thread Name :"+Thread.currentThread().getName());
	
	System.out.println("======================================");
	System.out.println("Accessing annotation example: "+jobService.getAllJobs());
	List<Map<String, Object>> list = jobService.getAllJobs();
	System.out.println("Job list :"+list);
	System.out.println("======================================");
	
	//*********** For retrieving stored key-value pairs ***********/
	JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
	String myValue = dataMap.getString("myKey");
	System.out.println("Value:" + myValue);

	//*********** For retrieving stored object, It will try to deserialize the bytes Object. ***********/
	/*
	SchedulerContext schedulerContext = null;
       try {
           schedulerContext = jobExecutionContext.getScheduler().getContext();
       } catch (SchedulerException e1) {
           e1.printStackTrace();
       }
       YourClass yourClassObject = (YourClass) schedulerContext.get("storedObjectKey");
	 */

	while(toStopFlag){
		try {
			System.out.println("Test Job Running... Thread Name :"+Thread.currentThread().getName());
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	System.out.println("Thread: "+ Thread.currentThread().getName() +" stopped.");
}
 
Example #28
Source File: TraceeContextInjector.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void injectContext(JobDataMap jobDataMap) {
	final TraceeFilterConfiguration configuration = backend.getConfiguration(profile);

	if (!backend.isEmpty() && configuration.shouldProcessContext(AsyncDispatch)) {
		jobDataMap.put(TraceeConstants.TPIC_HEADER, backend.getConfiguration(profile).filterDeniedParams(backend.copyToMap(), AsyncDispatch));
	}
}
 
Example #29
Source File: QuartzSchedulerSPI.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #30
Source File: JmsHelper.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
public static InitialContext getInitialContext(final JobDataMap jobDataMap) throws NamingException
{
    
    Hashtable params = new Hashtable(2);
    
    String initialContextFactory =
        jobDataMap.getString(INITIAL_CONTEXT_FACTORY);

    if (initialContextFactory != null) {
        params.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    }
    
    String providerUrl = jobDataMap.getString(PROVIDER_URL);
    if (providerUrl != null) {
        params.put(Context.PROVIDER_URL, providerUrl);
    }

    String principal = jobDataMap.getString(PRINCIPAL);
    if ( principal != null ) {
        params.put( Context.SECURITY_PRINCIPAL, principal );
    }

    String credentials = jobDataMap.getString(CREDENTIALS);
    if ( credentials != null ) {
        params.put( Context.SECURITY_CREDENTIALS, credentials );
    }

    if (params.size() == 0) {
        return new InitialContext();
    } else {
        return new InitialContext(params);
    }
    
}