Search in sources :

Example 1 with Job

use of org.quartz.Job in project sling by apache.

the class QuartzJobExecutor method execute.

/**
     * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
     */
@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {
    final JobDataMap data = context.getJobDetail().getJobDataMap();
    final JobDesc desc = new JobDesc(data);
    final Logger logger = (Logger) data.get(QuartzScheduler.DATA_MAP_LOGGER);
    // check run on information
    if (!shouldRun(logger, desc)) {
        return;
    }
    String origThreadName = Thread.currentThread().getName();
    try {
        Thread.currentThread().setName(origThreadName + "-" + desc.name);
        logger.debug("Executing job {}", desc);
        if (desc.job instanceof org.apache.sling.commons.scheduler.Job) {
            @SuppressWarnings("unchecked") final Map<String, Serializable> configuration = (Map<String, Serializable>) data.get(QuartzScheduler.DATA_MAP_CONFIGURATION);
            final JobContext jobCtx = new JobContextImpl(desc.name, configuration);
            ((org.apache.sling.commons.scheduler.Job) desc.job).execute(jobCtx);
        } else if (desc.job instanceof Runnable) {
            ((Runnable) desc.job).run();
        } else {
            logger.error("Scheduled job {} is neither a job nor a runnable: {}", desc);
        }
    } catch (final Throwable t) {
        // if this is a quartz exception, rethrow it
        if (t instanceof JobExecutionException) {
            throw (JobExecutionException) t;
        }
        // there is nothing we can do here, so we just log
        logger.error("Exception during job execution of " + desc + " : " + t.getMessage(), t);
    } finally {
        Thread.currentThread().setName(origThreadName);
    }
}
Also used : JobDataMap(org.quartz.JobDataMap) Serializable(java.io.Serializable) Logger(org.slf4j.Logger) JobExecutionException(org.quartz.JobExecutionException) JobContext(org.apache.sling.commons.scheduler.JobContext) Job(org.quartz.Job) JobDataMap(org.quartz.JobDataMap) Map(java.util.Map)

Example 2 with Job

use of org.quartz.Job in project opennms by OpenNMS.

the class ImportSchedulerIT method createJobAndVerifyImportJobFactoryIsRegistered.

@Test
public void createJobAndVerifyImportJobFactoryIsRegistered() throws SchedulerException, InterruptedException {
    RequisitionDef def = m_dao.getDefs().get(0);
    JobDetail detail = new JobDetailImpl("test", ImportScheduler.JOB_GROUP, ImportJob.class, false, false);
    detail.getJobDataMap().put(ImportJob.URL, def.getImportUrlResource().orElse(null));
    detail.getJobDataMap().put(ImportJob.RESCAN_EXISTING, def.getRescanExisting());
    class MyBoolWrapper {

        volatile Boolean m_called = false;

        public Boolean getCalled() {
            return m_called;
        }

        public void setCalled(Boolean called) {
            m_called = called;
        }
    }
    final MyBoolWrapper callTracker = new MyBoolWrapper();
    m_importScheduler.getScheduler().getListenerManager().addTriggerListener(new TriggerListener() {

        @Override
        public String getName() {
            return "TestTriggerListener";
        }

        @Override
        public void triggerComplete(Trigger trigger, JobExecutionContext context, Trigger.CompletedExecutionInstruction triggerInstructionCode) {
            LOG.info("triggerComplete called on trigger listener");
            callTracker.setCalled(true);
        }

        @Override
        public void triggerFired(Trigger trigger, JobExecutionContext context) {
            LOG.info("triggerFired called on trigger listener");
            Job jobInstance = context.getJobInstance();
            if (jobInstance instanceof ImportJob) {
                Assert.assertNotNull(((ImportJob) jobInstance).getProvisioner());
                Assert.assertTrue(context.getJobDetail().getJobDataMap().containsKey(ImportJob.URL));
                Assert.assertEquals("dns://localhost/localhost", context.getJobDetail().getJobDataMap().get(ImportJob.URL));
                Assert.assertTrue(context.getJobDetail().getJobDataMap().containsKey(ImportJob.RESCAN_EXISTING));
                Assert.assertEquals("dbonly", context.getJobDetail().getJobDataMap().get(ImportJob.RESCAN_EXISTING));
            }
            callTracker.setCalled(true);
        }

        @Override
        public void triggerMisfired(Trigger trigger) {
            LOG.info("triggerMisFired called on trigger listener");
            callTracker.setCalled(true);
        }

        @Override
        public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {
            LOG.info("vetoJobExecution called on trigger listener");
            callTracker.setCalled(true);
            return false;
        }
    });
    Calendar testCal = Calendar.getInstance();
    testCal.add(Calendar.SECOND, 5);
    SimpleTriggerImpl trigger = new SimpleTriggerImpl("test", ImportScheduler.JOB_GROUP, testCal.getTime());
    m_importScheduler.getScheduler().scheduleJob(detail, trigger);
    m_importScheduler.start();
    int callCheck = 0;
    while (!callTracker.getCalled() && callCheck++ < 2) {
        Thread.sleep(5000);
    }
// TODO: need to fix the interrupted exception that occurs in the provisioner
}
Also used : SimpleTriggerImpl(org.quartz.impl.triggers.SimpleTriggerImpl) Calendar(java.util.Calendar) TriggerListener(org.quartz.TriggerListener) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) JobDetailImpl(org.quartz.impl.JobDetailImpl) JobExecutionContext(org.quartz.JobExecutionContext) RequisitionDef(org.opennms.netmgt.config.provisiond.RequisitionDef) Job(org.quartz.Job) Test(org.junit.Test)

Example 3 with Job

use of org.quartz.Job in project karaf by apache.

the class QuartzJobExecutor method execute.

/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 */
public void execute(final JobExecutionContext context) throws JobExecutionException {
    final JobDataMap data = context.getJobDetail().getJobDataMap();
    final Object job = data.get(QuartzScheduler.DATA_MAP_OBJECT);
    final Logger logger = (Logger) data.get(QuartzScheduler.DATA_MAP_LOGGER);
    try {
        logger.debug("Executing job {} with name {}", job, data.get(QuartzScheduler.DATA_MAP_NAME));
        if (job instanceof org.apache.karaf.scheduler.Job) {
            final InternalScheduleOptions options = (InternalScheduleOptions) data.get(QuartzScheduler.DATA_MAP_OPTIONS);
            final String name = (String) data.get(QuartzScheduler.DATA_MAP_NAME);
            final JobContext jobCtx = new JobContextImpl(name, options.configuration);
            ((org.apache.karaf.scheduler.Job) job).execute(jobCtx);
        } else if (job instanceof Runnable) {
            ((Runnable) job).run();
        } else {
            logger.error("Scheduled job {} is neither a job nor a runnable.", job);
        }
    } catch (final Throwable t) {
        // there is nothing we can do here, so we just log
        logger.error("Exception during job execution of " + job + " : " + t.getMessage(), t);
    }
}
Also used : JobDataMap(org.quartz.JobDataMap) JobContext(org.apache.karaf.scheduler.JobContext) Logger(org.slf4j.Logger) Job(org.quartz.Job)

Example 4 with Job

use of org.quartz.Job in project xwiki-platform by xwiki.

the class SchedulerPlugin method scheduleJob.

public boolean scheduleJob(BaseObject object, XWikiContext context) throws SchedulerPluginException {
    boolean scheduled = true;
    try {
        // compute the job unique Id
        String xjob = getObjectUniqueId(object, context);
        // Load the job class.
        // Note: Remember to always use the current thread's class loader and not the container's
        // (Class.forName(...)) since otherwise we will not be able to load classes installed with EM.
        ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
        String jobClassName = object.getStringValue("jobClass");
        Class<Job> jobClass = (Class<Job>) Class.forName(jobClassName, true, currentThreadClassLoader);
        // Build the new job.
        JobBuilder jobBuilder = JobBuilder.newJob(jobClass);
        jobBuilder.withIdentity(xjob);
        jobBuilder.storeDurably();
        JobDataMap data = new JobDataMap();
        // Let's prepare an execution context...
        XWikiContext stubContext = prepareJobStubContext(object, context);
        data.put("context", stubContext);
        data.put("xcontext", stubContext);
        data.put("xwiki", new com.xpn.xwiki.api.XWiki(context.getWiki(), stubContext));
        data.put("xjob", object);
        data.put("services", Utils.getComponent(ScriptServiceManager.class));
        jobBuilder.setJobData(data);
        getScheduler().addJob(jobBuilder.build(), true);
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
        triggerBuilder.withIdentity(xjob);
        triggerBuilder.forJob(xjob);
        triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(object.getStringValue("cron")));
        Trigger trigger = triggerBuilder.build();
        JobState status = getJobStatus(object, context);
        switch(status.getQuartzState()) {
            case PAUSED:
                // a paused job must be resumed, not scheduled
                break;
            case NORMAL:
                if (getTrigger(object, context).compareTo(trigger) != 0) {
                    LOGGER.debug("Reschedule Job: [{}]", object.getStringValue("jobName"));
                }
                getScheduler().rescheduleJob(trigger.getKey(), trigger);
                break;
            case NONE:
                LOGGER.debug("Schedule Job: [{}]", object.getStringValue("jobName"));
                getScheduler().scheduleJob(trigger);
                LOGGER.info("XWiki Job Status: [{}]", object.getStringValue("status"));
                if (object.getStringValue("status").equals("Paused")) {
                    getScheduler().pauseJob(new JobKey(xjob));
                    saveStatus("Paused", object, context);
                } else {
                    saveStatus("Normal", object, context);
                }
                break;
            default:
                LOGGER.debug("Schedule Job: [{}]", object.getStringValue("jobName"));
                getScheduler().scheduleJob(trigger);
                saveStatus("Normal", object, context);
                break;
        }
    } catch (SchedulerException e) {
        throw new SchedulerPluginException(SchedulerPluginException.ERROR_SCHEDULERPLUGIN_SCHEDULE_JOB, "Error while scheduling job " + object.getStringValue("jobName"), e);
    } catch (ClassNotFoundException e) {
        throw new SchedulerPluginException(SchedulerPluginException.ERROR_SCHEDULERPLUGIN_JOB_XCLASS_NOT_FOUND, "Error while loading job class for job : " + object.getStringValue("jobName"), e);
    } catch (XWikiException e) {
        throw new SchedulerPluginException(SchedulerPluginException.ERROR_SCHEDULERPLUGIN_JOB_XCLASS_NOT_FOUND, "Error while saving job status for job : " + object.getStringValue("jobName"), e);
    }
    return scheduled;
}
Also used : JobDataMap(org.quartz.JobDataMap) SchedulerException(org.quartz.SchedulerException) JobBuilder(org.quartz.JobBuilder) XWikiContext(com.xpn.xwiki.XWikiContext) ScriptServiceManager(org.xwiki.script.service.ScriptServiceManager) JobKey(org.quartz.JobKey) Trigger(org.quartz.Trigger) Job(org.quartz.Job) XWikiException(com.xpn.xwiki.XWikiException)

Example 5 with Job

use of org.quartz.Job in project spring-boot by spring-projects.

the class QuartzEndpointTests method quartzJobWithSensitiveDataMap.

@Test
void quartzJobWithSensitiveDataMap() throws SchedulerException {
    JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").usingJobData("user", "user").usingJobData("password", "secret").usingJobData("url", "https://user:secret@example.com").build();
    mockJobs(job);
    QuartzJobDetails jobDetails = this.endpoint.quartzJob("samples", "hello");
    assertThat(jobDetails.getData()).containsOnly(entry("user", "user"), entry("password", "******"), entry("url", "https://user:******@example.com"));
}
Also used : JobDetail(org.quartz.JobDetail) QuartzJobDetails(org.springframework.boot.actuate.quartz.QuartzEndpoint.QuartzJobDetails) Job(org.quartz.Job) DelegatingJob(org.springframework.scheduling.quartz.DelegatingJob) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

Job (org.quartz.Job)17 JobDetail (org.quartz.JobDetail)9 JobDataMap (org.quartz.JobDataMap)6 SchedulerException (org.quartz.SchedulerException)5 Trigger (org.quartz.Trigger)5 CronScheduleBuilder (org.quartz.CronScheduleBuilder)4 JobBuilder (org.quartz.JobBuilder)4 Date (java.util.Date)3 Scheduler (org.quartz.Scheduler)3 Serializable (java.io.Serializable)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 JobExecutionContext (org.quartz.JobExecutionContext)2 JobKey (org.quartz.JobKey)2 SimpleScheduleBuilder (org.quartz.SimpleScheduleBuilder)2 TriggerBuilder (org.quartz.TriggerBuilder)2 Logger (org.slf4j.Logger)2 ScheduleTrigger (com.monitor.model.task.ScheduleTrigger)1 Values (com.searchcode.app.config.Values)1 IRepo (com.searchcode.app.dao.IRepo)1