Java Code Examples for org.quartz.SchedulerException

The following examples show how to use org.quartz.SchedulerException. These examples are extracted from open source projects. 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 Project: mercury   Source File: AdminEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{name}")
@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_HTML})
public Object startJob(@PathParam("name") String name) throws AppException, SchedulerException, IOException {
    ScheduledJob job = MainScheduler.getJob(name);
    if (job == null) {
        throw new AppException(404, "Job "+name+" not found");
    }
    if (job.startTime != null) {
        throw new IllegalArgumentException("Job "+name+" already started");
    }
    PostOffice.getInstance().broadcast(SCHEDULER_SERVICE, new Kv(ORIGIN, Platform.getInstance().getOrigin()),
                                        new Kv(TYPE, START), new Kv(JOB_ID, name));
    MainScheduler.startJob(job.name);
    Map<String, Object> result = new HashMap<>();
    result.put("type", "start");
    result.put("message", "Job "+name+" started");
    result.put("time", new Date());
    return result;
}
 
Example 2
Source Project: seed   Source File: QssService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取所有计划中的QuartzJob
 */
List<ScheduleTask> getAllJob(){
    try{
        List<ScheduleTask> taskList = new ArrayList<>();
        Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyJobGroup());
        for(JobKey jobKey : jobKeys){
            List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
            for(Trigger trigger : triggers){
                taskList.add(this.convertToScheduleTask(jobKey, trigger));
            }
        }
        return taskList;
    }catch(SchedulerException e){
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "获取所有计划中的QuartzJob失败", e);
    }
}
 
Example 3
Source Project: smarthome   Source File: ScriptExecution.java    License: 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 4
Source Project: AsuraFramework   Source File: StdSchedulerFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Returns a handle to the Scheduler produced by this factory.
 * </p>
 *
 * <p>
 * If one of the <code>initialize</code> methods has not be previously
 * called, then the default (no-arg) <code>initialize()</code> method
 * will be called by this method.
 * </p>
 */
public Scheduler getScheduler() throws SchedulerException {
    if (cfg == null) {
        initialize();
    }

    SchedulerRepository schedRep = SchedulerRepository.getInstance();

    Scheduler sched = schedRep.lookup(getSchedulerName());

    if (sched != null) {
        if (sched.isShutdown()) {
            schedRep.remove(getSchedulerName());
        } else {
            return sched;
        }
    }

    sched = instantiate();

    return sched;
}
 
Example 5
Source Project: opencron   Source File: JobController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping("/edit")
public void edit(HttpSession session,HttpServletResponse response,Job job) throws SchedulerException {
    Job jober = jobService.getJob(job.getJobId());
    if (!jobService.checkJobOwner(session,jober.getUserId())) return;
    jober.setExecType(job.getExecType());
    jober.setCronType(job.getCronType());
    jober.setCommand(DigestUtils.passBase64(job.getCommand()));
    jober.setJobName(job.getJobName());
    jober.setRedo(job.getRedo());
    jober.setRunCount(job.getRunCount());
    jober.setWarning(job.getWarning());
    jober.setTimeout(job.getTimeout());
    if (jober.getWarning()) {
        jober.setMobiles(job.getMobiles());
        jober.setEmailAddress(job.getEmailAddress());
    }
    jober.setComment(job.getComment());
    jober.setUpdateTime(new Date());
    jobService.addOrUpdate(jober);
    schedulerService.syncJobTigger(jober.getJobId(),executeService);
    WebUtils.writeHtml(response, "success");
}
 
Example 6
/**
 * Delete all quartz scheduler jobs of the group <code>Dropbox</code>.
 */
private void cancelAllJobs() {
    try {
        Set<JobKey> jobKeys = scheduler.getJobKeys(jobGroupEquals(GCAL_SCHEDULER_GROUP));
        if (jobKeys.size() > 0) {
            scheduler.deleteJobs(new ArrayList<JobKey>(jobKeys));
            logger.debug("Found {} Google Calendar Upload-Jobs to delete from DefaulScheduler (keys={})",
                    jobKeys.size(), jobKeys);
        } else {
            logger.debug("Not found Google Calendar Upload to remove");
        }

    } catch (SchedulerException e) {
        logger.warn("Couldn't remove Google Calendar Upload-Job: {}", e.getMessage());
    }
}
 
Example 7
Source Project: spacewalk   Source File: SchedulerKernel.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Shutsdown the application
 */
protected void shutdown() {
    try {
        SchedulerKernel.scheduler.standby();
        SchedulerKernel.scheduler.shutdown();
    }
    catch (SchedulerException e) {
        // TODO Figure out what to do with this guy
        e.printStackTrace();
    }
    finally {
        MessageQueue.stopMessaging();
        HibernateFactory.closeSessionFactory();
        // Wake up thread waiting in startup() so it can exit
        synchronized (this.shutdownLock) {
            this.shutdownLock.notify();
        }
    }
}
 
Example 8
Source Project: syncope   Source File: SchedulingPullActions.java    License: 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 9
Source Project: open-capacity-platform   Source File: XxlJobServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ReturnT<String> remove(int id) {
	XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
       String group = String.valueOf(xxlJobInfo.getJobGroup());
       String name = String.valueOf(xxlJobInfo.getId());

	try {
		XxlJobDynamicScheduler.removeJob(name, group);
		xxlJobInfoDao.delete(id);
		xxlJobLogDao.delete(id);
		xxlJobLogGlueDao.deleteByJobId(id);
		return ReturnT.SUCCESS;
	} catch (SchedulerException e) {
		logger.error(e.getMessage(), e);
	}
	return ReturnT.FAIL;
}
 
Example 10
Source Project: smarthome   Source File: TimerImpl.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean reschedule(AbstractInstant newTime) {
    try {
        Trigger trigger = newTrigger().startAt(newTime.toDate()).build();
        Date nextTriggerTime = scheduler.rescheduleJob(triggerKey, trigger);
        if (nextTriggerTime == null) {
            logger.debug("Scheduling a new job job '{}' because the original has already run", jobKey.toString());
            JobDetail job = newJob(TimerExecutionJob.class).withIdentity(jobKey).usingJobData(dataMap).build();
            TimerImpl.scheduler.scheduleJob(job, trigger);
        }
        this.triggerKey = trigger.getKey();
        this.cancelled = false;
        this.terminated = false;
        return true;
    } catch (SchedulerException e) {
        logger.warn("An error occurred while rescheduling the job '{}': {}", jobKey.toString(), e.getMessage());
        return false;
    }
}
 
Example 11
Source Project: deltaspike   Source File: AbstractQuartzScheduler.java    License: Apache License 2.0 6 votes vote down vote up
private Trigger createTrigger(Scheduled scheduled, JobKey jobKey, String cronExpression) throws SchedulerException
{
    UUID triggerKey = UUID.randomUUID();

    if (!scheduled.cronExpression().endsWith(cronExpression))
    {
        createExpressionObserverJob(jobKey, triggerKey, scheduled.cronExpression(), cronExpression);
    }

    Trigger trigger = TriggerBuilder.newTrigger()
            .forJob(jobKey)
            .withIdentity(triggerKey.toString())
            .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
            .build();
    return trigger;
}
 
Example 12
Source Project: javamelody   Source File: QuartzAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public void addGlobalJobListener(JobListener jobGlobalListener) throws SchedulerException {
	final Scheduler defaultScheduler;
	if (Parameter.QUARTZ_DEFAULT_LISTENER_DISABLED.getValueAsBoolean()) {
		defaultScheduler = null;
		LOG.debug("Initialization of Quartz default listener has been disabled");
	} else {
		defaultScheduler = StdSchedulerFactory.getDefaultScheduler();
		defaultScheduler.addGlobalJobListener(jobGlobalListener);
	}
	for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
		if (scheduler != defaultScheduler) {
			scheduler.addGlobalJobListener(jobGlobalListener);
		}
	}
}
 
Example 13
Source Project: WeEvent   Source File: QuartzManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * get the job message
 *
 * @param jobName
 * @return
 */
public CEPRule getJobDetail(String jobName) throws SchedulerException, BrokerException {
    JobDetail job = scheduler.getJobDetail(new JobKey(jobName, "rule"));
    if (!StringUtils.isEmpty(job.getJobDataMap().get("rule"))) {
        return JsonHelper.json2Object(job.getJobDataMap().get("rule").toString(), CEPRule.class);
    }
    return null;
}
 
Example 14
Source Project: sunbird-lms-service   Source File: SchedulerManager.java    License: MIT License 5 votes vote down vote up
@Override
public void run() {
  ProjectLogger.log(
      "SchedulerManager:ResourceCleanUp: started resource cleanup for Quartz job.",
      LoggerEnum.INFO);
  try {
    scheduler.shutdown();
  } catch (SchedulerException e) {
    ProjectLogger.log(e.getMessage(), e);
  }
  ProjectLogger.log(
      "SchedulerManager:ResourceCleanUp: completed resource cleanup Quartz job.",
      LoggerEnum.INFO);
}
 
Example 15
Source Project: griffin   Source File: JobServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * deleteJobsRelateToMeasure
 * 1. search jobs related to measure
 * 2. deleteJob
 *
 * @param measureId measure id
 */
public void deleteJobsRelateToMeasure(Long measureId) throws
    SchedulerException {
    List<AbstractJob> jobs = jobRepo.findByMeasureIdAndDeleted(measureId,
        false);
    if (CollectionUtils.isEmpty(jobs)) {
        LOGGER.info("Measure id {} has no related jobs.", measureId);
        return;
    }
    for (AbstractJob job : jobs) {
        JobOperator op = getJobOperator(job);
        op.delete(job);
    }
}
 
Example 16
@Test
public void assertRescheduleJobIfShutdown() throws SchedulerException {
    ReflectionUtils.setFieldValue(jobScheduleController, "scheduler", scheduler);
    when(scheduler.isShutdown()).thenReturn(true);
    jobScheduleController.rescheduleJob("0/1 * * * * ?");
    verify(scheduler, times(0)).rescheduleJob(eq(TriggerKey.triggerKey("test_job_Trigger")), any());
}
 
Example 17
Source Project: openhab1-addons   Source File: PlugwiseBinding.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void execute() {
    if (isProperlyConfigured()) {
        try {
            Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
            scheduleJobs(sched);
        } catch (SchedulerException e) {
            logger.error("An exception occurred while getting a reference to the Quartz Scheduler ({})",
                    e.getMessage());
        }
    }
}
 
Example 18
/**
 * Reschedule job.
 * 
 * @param cron CRON expression
 */
public synchronized void rescheduleJob(final String cron) {
    try {
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(TriggerKey.triggerKey(triggerIdentity));
        if (!scheduler.isShutdown() && null != trigger && !cron.equals(trigger.getCronExpression())) {
            scheduler.rescheduleJob(TriggerKey.triggerKey(triggerIdentity), createTrigger(cron));
        }
    } catch (final SchedulerException ex) {
        throw new JobSystemException(ex);
    }
}
 
Example 19
Source Project: RuoYi-Vue   Source File: SysJobServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * 立即运行任务
 * 
 * @param job 调度信息
 */
@Override
@Transactional
public void run(SysJob job) throws SchedulerException
{
    Long jobId = job.getJobId();
    String jobGroup = job.getJobGroup();
    SysJob properties = selectJobById(job.getJobId());
    // 参数
    JobDataMap dataMap = new JobDataMap();
    dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
    scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
}
 
Example 20
@Test
void scheduleInvalidCronExpression() throws SchedulerException {
  ScheduledJob scheduledJob = scheduledJobFactory.create();
  scheduledJob.setId(id);
  scheduledJob.set(ScheduledJobMetadata.CRON_EXPRESSION, "XXX");
  scheduledJob.set(ScheduledJobMetadata.NAME, "name");
  scheduledJob.set(ScheduledJobMetadata.ACTIVE, false);
  scheduledJob.setType(scheduledJobType);

  assertThrows(MolgenisValidationException.class, () -> jobScheduler.schedule(scheduledJob));
}
 
Example 21
Source Project: nexus-public   Source File: QuartzSchedulerSPI.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks the last run time against its last trigger fire time.
 * If the trigger's last fire time doesn't match with the jobs last fire time,
 * then the {@link TaskState} is set to interrupted
 *
 * @param nexusLastRunTime - approximate time at which the last instance of nexus was shutdown
 */
private void updateLastRunStateInfo(final JobDetail jobDetail, final Optional<Date> nexusLastRunTime)
    throws SchedulerException
{
  Optional<Date> latestFireWrapper = scheduler.getTriggersOfJob(jobDetail.getKey()).stream()
      .filter(Objects::nonNull)
      .map(Trigger::getPreviousFireTime)
      .filter(Objects::nonNull)
      .max(Date::compareTo);

  if (latestFireWrapper.isPresent()) {
    TaskConfiguration taskConfig = configurationOf(jobDetail);
    Date latestFire = latestFireWrapper.get();

    if (!taskConfig.hasLastRunState() || taskConfig.getLastRunState().getRunStarted().before(latestFire)) {
      long estimatedDuration = Math.max(nexusLastRunTime.orElse(latestFire).getTime() - latestFire.getTime(), 0);
      taskConfig.setLastRunState(INTERRUPTED, latestFire, estimatedDuration);

      log.warn("Updating lastRunState to interrupted for jobKey {} taskConfig: {}", jobDetail.getKey(), taskConfig);
      try {
        updateJobData(jobDetail, taskConfig);
        scheduler.addJob(jobDetail, true, true);
      }
      catch (RuntimeException e) {
        log.warn("Problem updating lastRunState to interrupted for jobKey {}", jobDetail.getKey(), e);
      }
    }
  }
}
 
Example 22
@Override
public void activate() {
    try {
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        super.activate();
    } catch (SchedulerException se) {
        logger.error("initializing scheduler throws exception", se);
    }
}
 
Example 23
@Override
protected AttributeList getAttributes(String[] attributes) throws SchedulerException {
    try {
        return server.getAttributes(getSchedulerObjectName(), attributes);
    } catch (Exception e) {
        throw new SchedulerException("Failed to get Scheduler MBean attributes: " + Arrays.asList(attributes), e);
    }
}
 
Example 24
protected void resetConsecutiveAlertsTriggered() {
	jobDataMap.put(CONSECUTIVE_ALERTS_TRIGGERED, "0");
	try {
		StdSchedulerFactory.getDefaultScheduler().addJob(jobDetail, true);
	} catch (SchedulerException e) {
		logger.error("resetConsecutiveAlertsTriggered", e);
	}
}
 
Example 25
Source Project: spring-boot-demo   Source File: JobController.java    License: MIT License 5 votes vote down vote up
/**
 * 删除定时任务
 */
@DeleteMapping
public ResponseEntity<ApiResponse> deleteJob(JobForm form) throws SchedulerException {
    if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
        return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
    }

    jobService.deleteJob(form);
    return new ResponseEntity<>(ApiResponse.msg("删除成功"), HttpStatus.OK);
}
 
Example 26
private boolean isRunning(JobExecutionContext context) {
  try {
    return context
        .getScheduler()
        .getCurrentlyExecutingJobs()
        .stream()
        .anyMatch(
            j ->
                j.getTrigger().equals(context.getTrigger())
                    && !j.getFireInstanceId().equals(context.getFireInstanceId()));
  } catch (SchedulerException e) {
    return false;
  }
}
 
Example 27
Source Project: dubai   Source File: JobDetailService.java    License: MIT License 5 votes vote down vote up
public void standby() {
    logger.debug("Standby scheduler.");

    try {
        localQuartzScheduler.standby();
    } catch (SchedulerException e) {
        logger.error(e.getMessage(), e);
        throw new ServiceException("Failed to standby scheduler.");
    }
}
 
Example 28
@Test
public void traceeContextShouldBePropagatedToJobByDecoratedTrigger() throws SchedulerException {
	schedulerBackend.put("testKey", "testValue");
	final JobDetail jobDetail = JobBuilder.newJob(TestJob.class).build();
	final Trigger trigger = TriggerBuilder.newTrigger().forJob(jobDetail).startNow().build();
	new TraceeContextInjector(schedulerBackend, Profile.DEFAULT).injectContext(trigger);
	scheduler.scheduleJob(jobDetail, trigger);
	verify(jobBackend, timeout(10000)).put(eq(TraceeConstants.INVOCATION_ID_KEY), any(String.class));
	assertThat(jobBackend.getValuesBeforeLastClear(), hasEntry("testKey", "testValue"));
}
 
Example 29
Source Project: lams   Source File: RemoteScheduler.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean unscheduleJobs(List<TriggerKey> triggerKeys)
        throws SchedulerException {
    try {
        return getRemoteScheduler().unscheduleJobs(triggerKeys);
    } catch (RemoteException re) {
        throw invalidateHandleCreateException(
                "Error communicating with remote scheduler.", re);
    }
}
 
Example 30
public JobDetail getJobDetail(SchedulerJob schedulerJob) {
    try {
        List<JobDetail> jobs = QuartzUtil.getAllJobDetails(scheduler);
        for (JobDetail job : jobs) {
            //System.out.println("*** jobName=" + job.getName() + "  name=" + schedulerJob.getPath());
            if (job.getKey().getName().equals(schedulerJob.getPath())) {
                return job;
            }
        }
    } catch (SchedulerException e) {
        throw new RuntimeException(e);
    }
    
    return null;
}