Search in sources :

Example 36 with JobExecutionContext

use of org.quartz.JobExecutionContext in project OpenClinica by OpenClinica.

the class ScheduledJobController method listScheduledJobs.

@RequestMapping("/listCurrentScheduledJobs")
public ModelMap listScheduledJobs(HttpServletRequest request, HttpServletResponse response) throws SchedulerException {
    Locale locale = LocaleResolver.getLocale(request);
    ResourceBundleProvider.updateLocale(locale);
    ModelMap gridMap = new ModelMap();
    String[] triggerNames;
    boolean showMoreLink = false;
    if (request.getParameter("showMoreLink") != null) {
        showMoreLink = Boolean.parseBoolean(request.getParameter("showMoreLink").toString());
    } else {
        showMoreLink = true;
    }
    request.setAttribute("showMoreLink", showMoreLink + "");
    // request.setAttribute("studySubjectId",studySubjectId);
    /*SubjectIdSDVFactory tableFactory = new SubjectIdSDVFactory();
        * @RequestParam("studySubjectId") int studySubjectId,*/
    request.setAttribute("imagePathPrefix", "../");
    ArrayList<String> pageMessages = (ArrayList<String>) request.getAttribute("pageMessages");
    if (pageMessages == null) {
        pageMessages = new ArrayList<String>();
    }
    request.setAttribute("pageMessages", pageMessages);
    List<JobExecutionContext> listCurrentJobs = new ArrayList<JobExecutionContext>();
    listCurrentJobs = scheduler.getCurrentlyExecutingJobs();
    Iterator<JobExecutionContext> itCurrentJobs = listCurrentJobs.iterator();
    List<String> currentJobList = new ArrayList<String>();
    while (itCurrentJobs.hasNext()) {
        JobExecutionContext temp = itCurrentJobs.next();
        currentJobList.add(temp.getTrigger().getJobName() + temp.getTrigger().getGroup());
    }
    String[] triggerGroups = scheduler.getTriggerGroupNames();
    List<SimpleTrigger> simpleTriggers = new ArrayList<SimpleTrigger>();
    int index1 = 0;
    for (String triggerGroup : triggerGroups) {
        logger.debug("Group: " + triggerGroup + " contains the following triggers");
        triggerNames = scheduler.getTriggerNames(triggerGroup);
        for (String triggerName : triggerNames) {
            int state = scheduler.getTriggerState(triggerName, triggerGroup);
            logger.debug("- " + triggerName);
            if (state != Trigger.STATE_PAUSED) {
                simpleTriggers.add(index1, (SimpleTrigger) scheduler.getTrigger(triggerName, triggerGroup));
                index1++;
            }
        }
    }
    List<ScheduledJobs> jobsScheduled = new ArrayList<ScheduledJobs>();
    int index = 0;
    for (SimpleTrigger st : simpleTriggers) {
        boolean isExecuting = currentJobList.contains(st.getJobName() + st.getGroup());
        ScheduledJobs jobs = new ScheduledJobs();
        ExtractPropertyBean epBean = null;
        if (st.getJobDataMap() != null) {
            epBean = (ExtractPropertyBean) st.getJobDataMap().get(EP_BEAN);
        }
        if (epBean != null) {
            StringBuilder checkbox = new StringBuilder();
            checkbox.append("<input style='margin-right: 5px' type='checkbox'/>");
            StringBuilder actions = new StringBuilder("<table><tr><td>");
            if (isExecuting) {
                actions.append("&nbsp;");
            } else {
                String contextPath = request.getContextPath();
                StringBuilder jsCodeString = new StringBuilder("this.form.method='GET'; this.form.action='").append(contextPath).append("/pages/cancelScheduledJob").append("';").append("this.form.theJobName.value='").append(st.getJobName()).append("';").append("this.form.theJobGroupName.value='").append(st.getJobGroup()).append("';").append("this.form.theTriggerName.value='").append(st.getName()).append("';").append("this.form.theTriggerGroupName.value='").append(st.getGroup()).append("';").append("this.form.submit();");
                actions.append("<td><input type=\"submit\" class=\"button\" value=\"Cancel Job\" ").append("name=\"cancelJob\" onclick=\"").append(jsCodeString.toString()).append("\" />");
            }
            actions.append("</td></tr></table>");
            jobs.setCheckbox(checkbox.toString());
            jobs.setDatasetId(epBean.getDatasetName());
            String fireTime = st.getStartTime() != null ? longFormat(locale).format(st.getStartTime()) : "";
            jobs.setFireTime(fireTime);
            if (st.getNextFireTime() != null) {
                jobs.setScheduledFireTime(longFormat(locale).format(st.getNextFireTime()));
            }
            jobs.setExportFileName(epBean.getExportFileName()[0]);
            jobs.setAction(actions.toString());
            jobs.setJobStatus(isExecuting ? "Currently Executing" : "Scheduled");
            jobsScheduled.add(index, jobs);
            index++;
        }
    }
    logger.debug("totalRows" + index);
    request.setAttribute("totalJobs", index);
    request.setAttribute("jobs", jobsScheduled);
    TableFacade facade = scheduledJobTableFactory.createTable(request, response);
    String sdvMatrix = facade.render();
    gridMap.addAttribute(SCHEDULED_TABLE_ATTRIBUTE, sdvMatrix);
    return gridMap;
}
Also used : Locale(java.util.Locale) ModelMap(org.springframework.ui.ModelMap) ArrayList(java.util.ArrayList) TableFacade(org.jmesa.facade.TableFacade) ScheduledJobs(org.akaza.openclinica.web.table.scheduledjobs.ScheduledJobs) ExtractPropertyBean(org.akaza.openclinica.bean.extract.ExtractPropertyBean) JobExecutionContext(org.quartz.JobExecutionContext) SimpleTrigger(org.quartz.SimpleTrigger) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 37 with JobExecutionContext

use of org.quartz.JobExecutionContext in project ballerina by ballerina-lang.

the class AppointmentJob method execute.

@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
    NativeCallableUnit fn = (NativeCallableUnit) jobDataMap.get(AppointmentConstants.BALLERINA_FUNCTION);
    Context balParentContext = (Context) jobDataMap.get(AppointmentConstants.BALLERINA_PARENT_CONTEXT);
    FunctionRefCPEntry onTriggerFunction = (FunctionRefCPEntry) jobDataMap.get(AppointmentConstants.BALLERINA_ON_TRIGGER_FUNCTION);
    FunctionRefCPEntry onErrorFunction = (FunctionRefCPEntry) jobDataMap.get(AppointmentConstants.BALLERINA_ON_ERROR_FUNCTION);
    ProgramFile programFile = balParentContext.getProgramFile();
    TaskExecutor.execute(fn, balParentContext, onTriggerFunction, onErrorFunction, programFile);
}
Also used : Context(org.ballerinalang.bre.Context) JobExecutionContext(org.quartz.JobExecutionContext) JobDataMap(org.quartz.JobDataMap) FunctionRefCPEntry(org.ballerinalang.util.codegen.cpentries.FunctionRefCPEntry) NativeCallableUnit(org.ballerinalang.model.NativeCallableUnit) ProgramFile(org.ballerinalang.util.codegen.ProgramFile)

Example 38 with JobExecutionContext

use of org.quartz.JobExecutionContext in project ovirt-engine by oVirt.

the class FixedDelayJobListener method jobWasExecuted.

/**
 * reschedule the job with a new trigger. The new trigger will fire within a
 * fixed time from the method execution.
 *
 * @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext,
 *      JobExecutionException)
 */
@Override
public void jobWasExecuted(JobExecutionContext context, JobExecutionException exception) {
    // Get the details of the job:
    JobDetail jobdetail = context.getJobDetail();
    JobDataMap data = jobdetail.getJobDataMap();
    // job and if not just exit:
    if (!data.containsKey(SchedulerUtilBaseImpl.FIXED_DELAY_VALUE)) {
        return;
    }
    // This Job might already have an unused trigger in place, use it
    List<? extends Trigger> triggersOfJob = null;
    try {
        triggersOfJob = context.getScheduler().getTriggersOfJob(context.getJobDetail().getKey());
    } catch (SchedulerException e) {
    // ignore
    }
    if (triggersOfJob != null && triggersOfJob.stream().filter(t -> t instanceof SimpleTrigger).anyMatch(t -> ((SimpleTrigger) t).getTimesTriggered() == 0)) {
        logger.debug("Not scheduling {} again as there is still an unfired trigger.", context.getJobDetail().getKey());
        return;
    } else {
        logger.debug("Rescheduling {} as there is no unfired trigger.", context.getJobDetail().getKey());
    }
    // generate the new trigger time
    String configValueName = data.getString(SchedulerUtilBaseImpl.CONFIGURABLE_DELAY_KEY_NAME);
    long delay;
    if (StringUtils.isEmpty(configValueName)) {
        delay = data.getLongValue(SchedulerUtilBaseImpl.FIXED_DELAY_VALUE);
    } else {
        ConfigValues configDelay = ConfigValues.valueOf(configValueName);
        delay = Config.<Integer>getValue(configDelay).longValue();
    }
    TimeUnit delayUnit = (TimeUnit) data.getWrappedMap().get(SchedulerUtilBaseImpl.FIXED_DELAY_TIME_UNIT);
    Date runTime = SchedulerUtilQuartzImpl.getFutureDate(delay, delayUnit);
    // generate the new trigger
    Trigger oldTrigger = context.getTrigger();
    TriggerKey oldTriggerKey = oldTrigger.getKey();
    Trigger newTrigger = newTrigger().withIdentity(oldTriggerKey).startAt(runTime).build();
    // schedule the new trigger
    sched.rescheduleAJob(oldTriggerKey.getName(), oldTriggerKey.getGroup(), newTrigger);
// SchedulerUtilQuartzImpl.getInstance().rescheduleAJob(oldTriggerName,
// oldTriggerGroup, newTrigger);
}
Also used : JobExecutionContext(org.quartz.JobExecutionContext) StringUtils(org.apache.commons.lang.StringUtils) Logger(org.slf4j.Logger) Date(java.util.Date) JobListener(org.quartz.JobListener) LoggerFactory(org.slf4j.LoggerFactory) ConfigValues(org.ovirt.engine.core.common.config.ConfigValues) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) TimeUnit(java.util.concurrent.TimeUnit) JobExecutionException(org.quartz.JobExecutionException) List(java.util.List) SchedulerException(org.quartz.SchedulerException) JobDataMap(org.quartz.JobDataMap) Trigger(org.quartz.Trigger) SimpleTrigger(org.quartz.SimpleTrigger) TriggerKey(org.quartz.TriggerKey) Config(org.ovirt.engine.core.common.config.Config) JobDetail(org.quartz.JobDetail) JobDataMap(org.quartz.JobDataMap) SchedulerException(org.quartz.SchedulerException) ConfigValues(org.ovirt.engine.core.common.config.ConfigValues) Date(java.util.Date) TriggerKey(org.quartz.TriggerKey) JobDetail(org.quartz.JobDetail) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) Trigger(org.quartz.Trigger) SimpleTrigger(org.quartz.SimpleTrigger) TimeUnit(java.util.concurrent.TimeUnit) SimpleTrigger(org.quartz.SimpleTrigger)

Example 39 with JobExecutionContext

use of org.quartz.JobExecutionContext in project midpoint by Evolveum.

the class TestTaskManagerBasic method test260LightweightSubtasksSuspension.

@Test
public void test260LightweightSubtasksSuspension() throws Exception {
    given();
    OperationResult result = createOperationResult();
    when();
    add(TASK_WITH_THREADS_TO_SUSPEND, result);
    waitForTaskStart(TASK_WITH_THREADS_TO_SUSPEND.oid, result, 15000, 500);
    TaskQuartzImpl task = getTaskWithResult(TASK_WITH_THREADS_TO_SUSPEND.oid, result);
    displayDumpable("taskAfterStart", task);
    // assertEquals(TaskExecutionStateType.RUNNING, task.getExecutionState()); // todo
    assertEquals(TaskSchedulingStateType.READY, task.getSchedulingState());
    // check the thread
    JobExecutionContext found = findJobForTask(task);
    JobExecutor executor = (JobExecutor) found.getJobInstance();
    assertNotNull("No job executor", executor);
    Thread thread = executor.getExecutingThread();
    assertNotNull("No executing thread", thread);
    // now let us suspend it - the handler should stop, as well as the subtasks
    boolean stopped = taskManager.suspendTask(task, 10000L, result);
    then();
    task.refresh(result);
    assertTrue("Task is not stopped", stopped);
    assertSuspended(task);
    Collection<? extends RunningLightweightTask> subtasks = mockParallelTaskHandler.getLastTaskExecuted().getLightweightAsynchronousSubtasks();
    assertEquals("Wrong number of subtasks", MockParallelTaskHandler.NUM_SUBTASKS, subtasks.size());
    for (RunningLightweightTask subtask : subtasks) {
        assertEquals("Wrong subtask state", TaskExecutionStateType.CLOSED, subtask.getExecutionState());
        MockParallelTaskHandler.MyLightweightTaskHandler handler = (MockParallelTaskHandler.MyLightweightTaskHandler) subtask.getLightweightTaskHandler();
        assertTrue("Handler has not run", handler.hasRun());
        assertTrue("Handler has not exited", handler.hasExited());
    }
}
Also used : JobExecutor(com.evolveum.midpoint.task.quartzimpl.run.JobExecutor) RunningLightweightTask(com.evolveum.midpoint.task.api.RunningLightweightTask) JobExecutionContext(org.quartz.JobExecutionContext) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Test(org.testng.annotations.Test)

Example 40 with JobExecutionContext

use of org.quartz.JobExecutionContext in project midpoint by Evolveum.

the class TestTaskManagerBasic method findJobForTask.

@NotNull
private JobExecutionContext findJobForTask(TaskQuartzImpl task) throws SchedulerException {
    List<JobExecutionContext> jobExecutionContexts = localScheduler.getQuartzScheduler().getCurrentlyExecutingJobs();
    JobExecutionContext found = null;
    for (JobExecutionContext jobExecutionContext : jobExecutionContexts) {
        if (task.getOid().equals(jobExecutionContext.getJobDetail().getKey().getName())) {
            found = jobExecutionContext;
            break;
        }
    }
    assertNotNull("Job for the task was not found", found);
    return found;
}
Also used : JobExecutionContext(org.quartz.JobExecutionContext) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

JobExecutionContext (org.quartz.JobExecutionContext)47 Test (org.junit.Test)20 JobDetail (org.quartz.JobDetail)20 JobDataMap (org.quartz.JobDataMap)13 Set (java.util.Set)10 JobExecutionException (org.quartz.JobExecutionException)10 List (java.util.List)8 SchedulerException (org.quartz.SchedulerException)8 VirtConsumerMap (org.candlepin.model.VirtConsumerMap)7 Job (org.quartz.Job)6 ArrayList (java.util.ArrayList)5 UnableToInterruptJobException (org.quartz.UnableToInterruptJobException)5 Consumer (org.candlepin.model.Consumer)4 InterruptableJob (org.quartz.InterruptableJob)4 Scheduler (org.quartz.Scheduler)4 Date (java.util.Date)3 Map (java.util.Map)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)2