Search in sources :

Example 41 with JobExecutionContext

use of org.quartz.JobExecutionContext in project zeppelin by apache.

the class CronJobListener method jobWasExecuted.

@Override
public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
    JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
    String noteId = jobDataMap.getString("noteId");
    Notebook notebook = (Notebook) jobDataMap.get("notebook");
    String noteName = "unknown";
    try {
        noteName = notebook.processNote(noteId, note -> {
            if (note == null) {
                LOGGER.warn("Failed to get note: {}", noteId);
                return "unknown";
            }
            return note.getName();
        });
    } catch (IOException e) {
        LOGGER.error("Failed to get note: {}", noteId, e);
    } finally {
        Timer.Sample sample = cronJobTimerSamples.remove(context);
        String result = StringUtils.defaultString(context.getResult().toString(), "unknown");
        LOGGER.info("cron job of noteId {} executed with result {}", noteId, result);
        if (sample != null) {
            Tag noteIdTag = Tag.of("nodeid", noteId);
            Tag nameTag = Tag.of("name", noteName);
            Tag statusTag = Tag.of("result", result);
            sample.stop(Metrics.timer("cronjob", Tags.of(noteIdTag, nameTag, statusTag)));
        } else {
            LOGGER.warn("No Timer.Sample for NoteId {} found", noteId);
        }
    }
}
Also used : JobExecutionContext(org.quartz.JobExecutionContext) Tag(io.micrometer.core.instrument.Tag) Tags(io.micrometer.core.instrument.Tags) Logger(org.slf4j.Logger) JobListener(org.quartz.JobListener) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) Notebook(org.apache.zeppelin.notebook.Notebook) Metrics(io.micrometer.core.instrument.Metrics) JobExecutionException(org.quartz.JobExecutionException) Timer(io.micrometer.core.instrument.Timer) JobDataMap(org.quartz.JobDataMap) Map(java.util.Map) JobDataMap(org.quartz.JobDataMap) Notebook(org.apache.zeppelin.notebook.Notebook) Timer(io.micrometer.core.instrument.Timer) IOException(java.io.IOException) Tag(io.micrometer.core.instrument.Tag)

Example 42 with JobExecutionContext

use of org.quartz.JobExecutionContext in project topcom-cloud by 545314690.

the class BriefingJob method execute.

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Long briefingTaskId = (Long) context.getMergedJobDataMap().get("briefingTaskId");
    BriefingTask briefingTask = briefingTaskManager.findById(briefingTaskId);
    logger.info("任务运行:" + briefingTask.getBriefingType() + ":" + briefingTaskId);
    /**
     * 生成月报
     */
    JSONObject briefing = null;
    try {
        briefing = (JSONObject) briefingCreator.create(briefingTask).get();
        logger.info("任务运行:生成报告成功");
    } catch (BusinessException | InterruptedException | ExecutionException e) {
        e.printStackTrace();
        logger.info("任务运行:生成报告失败");
    }
    List<Contact> contacts = briefingTask.getContacts();
    // 过滤出email联系人
    Set<String> emailSet = contacts.stream().filter(contact -> Contact.Type.EMAIL.equals(contact.getType())).map(contact -> contact.getAccount()).collect(Collectors.toSet());
    if (emailSet.size() > 0) {
        SenderFactory emailSenderFactory = new EmailSenderFactory();
        Sender emailSender = emailSenderFactory.create();
        String[] emails = {};
        emails = emailSet.toArray(emails);
        if (briefing != null) {
            try {
                BriefingEmail briefingEmail = new BriefingEmail().create(emails, briefing);
                briefingEmail.setSubject(SUBJECT);
                emailSender.send(briefingEmail);
            } catch (IOException | TemplateException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : JobExecutionContext(org.quartz.JobExecutionContext) SenderFactory(com.topcom.cms.yuqing.task.sender.factory.SenderFactory) TemplateException(freemarker.template.TemplateException) Logger(org.jboss.logging.Logger) BusinessException(com.topcom.cms.exception.BusinessException) Autowired(org.springframework.beans.factory.annotation.Autowired) Set(java.util.Set) Job(org.quartz.Job) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) EmailSenderFactory(com.topcom.cms.yuqing.task.sender.factory.EmailSenderFactory) JobExecutionException(org.quartz.JobExecutionException) ExecutionException(java.util.concurrent.ExecutionException) BriefingEmail(com.topcom.cms.yuqing.vo.email.BriefingEmail) Component(org.springframework.stereotype.Component) List(java.util.List) BriefingTask(com.topcom.cms.yuqing.domain.BriefingTask) BriefingTaskManager(com.topcom.cms.yuqing.service.BriefingTaskManager) JSONObject(net.sf.json.JSONObject) Contact(com.topcom.cms.yuqing.domain.Contact) Sender(com.topcom.cms.yuqing.task.sender.Sender) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) BriefingEmail(com.topcom.cms.yuqing.vo.email.BriefingEmail) TemplateException(freemarker.template.TemplateException) BusinessException(com.topcom.cms.exception.BusinessException) IOException(java.io.IOException) JobExecutionException(org.quartz.JobExecutionException) ExecutionException(java.util.concurrent.ExecutionException) Contact(com.topcom.cms.yuqing.domain.Contact) Sender(com.topcom.cms.yuqing.task.sender.Sender) BusinessException(com.topcom.cms.exception.BusinessException) EmailSenderFactory(com.topcom.cms.yuqing.task.sender.factory.EmailSenderFactory) JSONObject(net.sf.json.JSONObject) SenderFactory(com.topcom.cms.yuqing.task.sender.factory.SenderFactory) EmailSenderFactory(com.topcom.cms.yuqing.task.sender.factory.EmailSenderFactory) BriefingTask(com.topcom.cms.yuqing.domain.BriefingTask) JobExecutionException(org.quartz.JobExecutionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 43 with JobExecutionContext

use of org.quartz.JobExecutionContext in project alfresco-repository by Alfresco.

the class LockingJobTest method testJobInClusterNotLocked.

@Test
public void testJobInClusterNotLocked() throws Exception {
    // mock the job context
    JobExecutionContext mockJobExecutionContext = mock(JobExecutionContext.class);
    // create the hb collector
    SimpleHBDataCollector simpleCollector = spy(new SimpleHBDataCollector("simpleCollector"));
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("collector", simpleCollector);
    jobDataMap.put("hbDataSenderService", mockDataSenderService);
    jobDataMap.put("jobLockService", mockJobLockService);
    JobDetail jobDetail = JobBuilder.newJob().setJobData(jobDataMap).ofType(LockingJob.class).build();
    when(mockJobExecutionContext.getJobDetail()).thenReturn(jobDetail);
    // collector job is not locked from an other collector
    String lockToken = "locked";
    Runnable r1 = () -> {
        // if a second job tries to get the lock before we finished that will raise the exception
        when(mockJobLockService.getLock(isA(QName.class), anyLong())).thenReturn(lockToken).thenThrow(new LockAcquisitionException("", ""));
        try {
            new LockingJob().execute(mockJobExecutionContext);
        } catch (JobExecutionException e) {
        // 
        } finally {
            // when we are finished an other job can have the lock
            when(mockJobLockService.getLock(isA(QName.class), anyLong())).thenReturn(lockToken);
        }
    };
    Runnable r2 = () -> {
        try {
            new LockingJob().execute(mockJobExecutionContext);
        } catch (JobExecutionException e) {
        // 
        }
    };
    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);
    t1.start();
    Thread.sleep(500);
    t2.start();
    // Wait for threads to finish before testing
    Thread.sleep(1000);
    // verify that we collected and send data but just one time
    verify(simpleCollector, Mockito.times(2)).collectData();
    verify(mockDataSenderService, Mockito.times(2)).sendData(any(List.class));
    verify(mockDataSenderService, Mockito.times(0)).sendData(any(HBData.class));
    verify(mockJobLockService, Mockito.times(2)).getLock(any(QName.class), anyLong());
    verify(mockJobLockService, Mockito.times(2)).refreshLock(eq(lockToken), any(QName.class), anyLong(), any(JobLockService.JobLockRefreshCallback.class));
}
Also used : JobDataMap(org.quartz.JobDataMap) QName(org.alfresco.service.namespace.QName) JobDetail(org.quartz.JobDetail) JobExecutionException(org.quartz.JobExecutionException) LockingJob(org.alfresco.heartbeat.jobs.LockingJob) JobExecutionContext(org.quartz.JobExecutionContext) LinkedList(java.util.LinkedList) List(java.util.List) HBData(org.alfresco.heartbeat.datasender.HBData) LockAcquisitionException(org.alfresco.repo.lock.LockAcquisitionException) Test(org.junit.Test)

Example 44 with JobExecutionContext

use of org.quartz.JobExecutionContext in project alfresco-repository by Alfresco.

the class LockingJobTest method testJobLocking.

@Test
public void testJobLocking() throws Exception {
    HBBaseDataCollector simpleCollector = mock(HBBaseDataCollector.class);
    when(simpleCollector.getCollectorId()).thenReturn("c1");
    when(simpleCollector.getCronExpression()).thenReturn("0 0 0 ? * *");
    // mock the job context
    JobExecutionContext mockJobExecutionContext = mock(JobExecutionContext.class);
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("collector", simpleCollector);
    jobDataMap.put("hbDataSenderService", mockDataSenderService);
    jobDataMap.put("jobLockService", mockJobLockService);
    JobDetail jobDetail = JobBuilder.newJob().setJobData(jobDataMap).ofType(LockingJob.class).build();
    when(mockJobExecutionContext.getJobDetail()).thenReturn(jobDetail);
    // Simulate job lock service
    String lockToken = "token";
    when(mockJobLockService.getLock(isA(QName.class), anyLong())).thenReturn(// first job gets the lock
    lockToken).thenThrow(// second job doesn't get the lock
    new LockAcquisitionException("", ""));
    // Run two heart beat jobs
    new LockingJob().execute(mockJobExecutionContext);
    new LockingJob().execute(mockJobExecutionContext);
    // Verify that the collector only collects data once, since only one job got the lock
    verify(simpleCollector, Mockito.times(1)).collectData();
    // Verify that data was passed to data sender
    verify(mockDataSenderService, Mockito.times(1)).sendData(any(List.class));
    verify(mockDataSenderService, Mockito.times(0)).sendData(any(HBData.class));
    // Verify that both jobs tried to get the lock
    verify(mockJobLockService, Mockito.times(2)).getLock(any(QName.class), anyLong());
    // Verify that a callback was registered once
    verify(mockJobLockService, Mockito.times(1)).refreshLock(eq(lockToken), any(QName.class), anyLong(), any(JobLockService.JobLockRefreshCallback.class));
}
Also used : JobDataMap(org.quartz.JobDataMap) JobDetail(org.quartz.JobDetail) LockingJob(org.alfresco.heartbeat.jobs.LockingJob) QName(org.alfresco.service.namespace.QName) HBBaseDataCollector(org.alfresco.heartbeat.HBBaseDataCollector) JobExecutionContext(org.quartz.JobExecutionContext) LinkedList(java.util.LinkedList) List(java.util.List) HBData(org.alfresco.heartbeat.datasender.HBData) LockAcquisitionException(org.alfresco.repo.lock.LockAcquisitionException) Test(org.junit.Test)

Example 45 with JobExecutionContext

use of org.quartz.JobExecutionContext in project weicoder by wdcode.

the class ExecutingJobsManager method shutdown.

/**
 * <p>
 * Halts the <code>QuartzScheduler</code>'s firing of <code>{@link org.quartz.Trigger}s</code>,
 * and cleans up all resources associated with the QuartzScheduler.
 * </p>
 *
 * <p>
 * The scheduler cannot be re-started.
 * </p>
 *
 * @param waitForJobsToComplete
 *          if <code>true</code> the scheduler will not allow this method
 *          to return until all currently executing jobs have completed.
 */
public void shutdown(boolean waitForJobsToComplete) {
    if (shuttingDown || closed) {
        return;
    }
    shuttingDown = true;
    getLog().info("Scheduler " + resources.getUniqueIdentifier() + " shutting down.");
    // boolean removeMgmtSvr = false;
    // if (registeredManagementServerBind != null) {
    // ManagementServer standaloneRestServer =
    // MGMT_SVR_BY_BIND.get(registeredManagementServerBind);
    // 
    // try {
    // standaloneRestServer.unregister(this);
    // 
    // if (!standaloneRestServer.hasRegistered()) {
    // removeMgmtSvr = true;
    // standaloneRestServer.stop();
    // }
    // } catch (Exception e) {
    // getLog().warn("Failed to shutdown the ManagementRESTService", e);
    // } finally {
    // if (removeMgmtSvr) {
    // MGMT_SVR_BY_BIND.remove(registeredManagementServerBind);
    // }
    // 
    // registeredManagementServerBind = null;
    // }
    // }
    standby();
    schedThread.halt(waitForJobsToComplete);
    notifySchedulerListenersShuttingdown();
    if ((resources.isInterruptJobsOnShutdown() && !waitForJobsToComplete) || (resources.isInterruptJobsOnShutdownWithWait() && waitForJobsToComplete)) {
        List<JobExecutionContext> jobs = getCurrentlyExecutingJobs();
        for (JobExecutionContext job : jobs) {
            if (job.getJobInstance() instanceof InterruptableJob)
                try {
                    ((InterruptableJob) job.getJobInstance()).interrupt();
                } catch (Throwable e) {
                    // do nothing, this was just a courtesy effort
                    getLog().warn("Encountered error when interrupting job {} during shutdown: {}", job.getJobDetail().getKey(), e);
                }
        }
    }
    resources.getThreadPool().shutdown(waitForJobsToComplete);
    closed = true;
    if (resources.getJMXExport()) {
        try {
            unregisterJMX();
        } catch (Exception e) {
        }
    }
    if (boundRemotely) {
        try {
            unBind();
        } catch (RemoteException re) {
        }
    }
    shutdownPlugins();
    resources.getJobStore().shutdown();
    notifySchedulerListenersShutdown();
    SchedulerRepository.getInstance().remove(resources.getName());
    holdToPreventGC.clear();
    getLog().info("Scheduler " + resources.getUniqueIdentifier() + " shutdown complete.");
}
Also used : InterruptableJob(org.quartz.InterruptableJob) JobExecutionContext(org.quartz.JobExecutionContext) RemoteException(java.rmi.RemoteException) ObjectAlreadyExistsException(org.quartz.ObjectAlreadyExistsException) RemoteException(java.rmi.RemoteException) JobExecutionException(org.quartz.JobExecutionException) UnableToInterruptJobException(org.quartz.UnableToInterruptJobException) SchedulerException(org.quartz.SchedulerException)

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