org.quartz.CronScheduleBuilder Java Examples

The following examples show how to use org.quartz.CronScheduleBuilder. 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: QuartzManagerUtils.java    From kafka-eagle with Apache License 2.0 6 votes vote down vote up
/** Add new job. */
public static void addJob(BaseJobContext jobContext, String jobName, Class<? extends Job> jobClass, String cron) {
	try {
		Scheduler sched = schedulerFactory.getScheduler();
		JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, KE_JOB_GROUP_NAME).build();
		jobDetail.getJobDataMap().put(AlarmQueue.JOB_PARAMS, jobContext);
		TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
		triggerBuilder.withIdentity("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
		triggerBuilder.startNow();
		triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
		CronTrigger trigger = (CronTrigger) triggerBuilder.build();
		sched.scheduleJob(jobDetail, trigger);
		if (!sched.isShutdown()) {
			sched.start();
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #2
Source File: ScheduleUtils.java    From ruoyiplus with MIT License 6 votes vote down vote up
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
        throws TaskException
{
    switch (job.getMisfirePolicy())
    {
        case ScheduleConstants.MISFIRE_DEFAULT:
            return cb;
        case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
            return cb.withMisfireHandlingInstructionIgnoreMisfires();
        case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
            return cb.withMisfireHandlingInstructionFireAndProceed();
        case ScheduleConstants.MISFIRE_DO_NOTHING:
            return cb.withMisfireHandlingInstructionDoNothing();
        default:
            throw new TaskException("The task misfire policy '" + job.getMisfirePolicy() + "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR);
    }
}
 
Example #3
Source File: ScheduleTaskService.java    From RCT with Apache License 2.0 6 votes vote down vote up
public List<String> getRecentTriggerTime(String cron) {
	List<String> list = new ArrayList<String>();
	if (!CronExpression.isValidExpression(cron)) {
		return list;
	}
	CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("date")
			.withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Date startTime = cronTrigger.getStartTime();
	for (int i = 0; i < 5; i++) {
		Date time = cronTrigger.getFireTimeAfter(startTime);
		list.add(sdf.format(time));
		startTime = time;
	}
	return list;
}
 
Example #4
Source File: AbstractQuartzTaskManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private CronScheduleBuilder handleCronScheduleMisfirePolicy(TaskInfo.TriggerInfo triggerInfo,
                                                            CronScheduleBuilder cb) throws TaskException {
    switch (triggerInfo.getMisfirePolicy()) {
    case DEFAULT:
        return cb;
    case IGNORE_MISFIRES:
        return cb.withMisfireHandlingInstructionIgnoreMisfires();
    case FIRE_AND_PROCEED:
        return cb.withMisfireHandlingInstructionFireAndProceed();
    case DO_NOTHING:
        return cb.withMisfireHandlingInstructionDoNothing();
    default:
        throw new TaskException("The task misfire policy '" + triggerInfo.getMisfirePolicy()
                                        + "' cannot be used in cron schedule tasks",
                                TaskException.Code.CONFIG_ERROR);
    }
}
 
Example #5
Source File: DynamicTask.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 注册 定时任务
 * @param task 定时任务对象
 * @throws SchedulerException
 */
private void scheduleJob(TSTimeTaskEntity task) throws SchedulerException {
	//build 要执行的任务
	JobDetail jobDetail = JobBuilder.newJob(MyClassLoader.getClassByScn(task.getClassName()))
			.withIdentity(task.getId())
		    .storeDurably()
		    .requestRecovery()
		    .build();
	//根据Cron表达式 build 触发时间对象
	CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
	//build 任务触发器
	CronTrigger cronTrigger = TriggerBuilder.newTrigger()
			.withIdentity("cron_" + task.getId())
			.withSchedule(cronScheduleBuilder)//标明触发时间
			.build();
	//向调度器注册 定时任务
	schedulerFactory.scheduleJob(jobDetail, cronTrigger);
}
 
Example #6
Source File: ScheduleUtils.java    From supplierShop with MIT License 6 votes vote down vote up
/**
 * 设置定时任务策略
 */
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
        throws TaskException
{
    switch (job.getMisfirePolicy())
    {
        case ScheduleConstants.MISFIRE_DEFAULT:
            return cb;
        case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
            return cb.withMisfireHandlingInstructionIgnoreMisfires();
        case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
            return cb.withMisfireHandlingInstructionFireAndProceed();
        case ScheduleConstants.MISFIRE_DO_NOTHING:
            return cb.withMisfireHandlingInstructionDoNothing();
        default:
            throw new TaskException("The task misfire policy '" + job.getMisfirePolicy()
                    + "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR);
    }
}
 
Example #7
Source File: ScheduleUtils.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 设置定时任务策略
 */
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
        throws TaskException
{
    switch (job.getMisfirePolicy())
    {
        case ScheduleConstants.MISFIRE_DEFAULT:
            return cb;
        case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
            return cb.withMisfireHandlingInstructionIgnoreMisfires();
        case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
            return cb.withMisfireHandlingInstructionFireAndProceed();
        case ScheduleConstants.MISFIRE_DO_NOTHING:
            return cb.withMisfireHandlingInstructionDoNothing();
        default:
            throw new TaskException("The task misfire policy '" + job.getMisfirePolicy()
                    + "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR);
    }
}
 
Example #8
Source File: SchedulerPushSource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public void produce(Map<String, String> lastOffsets, int maxBatchSize) {
  try {
    JobDetail job = JobBuilder.newJob(SchedulerJob.class)
        .withIdentity(context.getPipelineId(), "dataCollectorJobGroup")
        .build();
    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(conf.cronExpression)
        .inTimeZone(TimeZone.getTimeZone(ZoneId.of(conf.timeZoneID)));
    cronTrigger = TriggerBuilder.newTrigger()
        .withIdentity(context.getPipelineId(), "dataCollectorJobGroup")
        .withSchedule(cronScheduleBuilder)
        .build();

    scheduler.getContext().put(PUSH_SOURCE_CONTEXT, context);
    scheduler.scheduleJob(job, cronTrigger);

    scheduler.start();

    while (!context.isStopped()) {
      dispatchErrors();
    }
  } catch (Exception e) {
    LOG.error(e.getMessage(), e);
    context.reportError(e);
  }
}
 
Example #9
Source File: CronService.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
public void schedule(Runnable r, String cronExpression, boolean longRunning) {
	try {
		JobDataMap jdm = new JobDataMap();
		jdm.put(RunnableRunner.KEY_RUNNABLE_OBJECT, r);
		jdm.put(RunnableRunner.KEY_PROPERTY_IS_LONGRUNNING_TASK, longRunning);
		jdm.put(RunnableRunner.KEY_CRON_EXPRESSION, cronExpression);

		String jobId = "Started at ms" + System.currentTimeMillis() + "; ns" + System.nanoTime();
		JobKey jobKey = new JobKey("JobKey:" + jobId);
		JobDetail jobDetail = JobBuilder.newJob(runnableRunner).usingJobData(jdm).withIdentity(jobKey).build();

		CronScheduleBuilder csb = CronScheduleBuilder.cronSchedule(cronExpression);
		CronTrigger trigger = TriggerBuilder.newTrigger().withSchedule(csb).build();

		scheduler.scheduleJob(jobDetail, trigger);
	} catch (Exception e) {
		throw new CronServiceException("Failed to start job", e);
	}
}
 
Example #10
Source File: ScheduleJobService.java    From springboot-quartz with MIT License 6 votes vote down vote up
private void addJob(ScheduleJob scheduleJob) throws Exception{  
  	checkNotNull(scheduleJob);
Preconditions.checkNotNull(StringUtils.isEmpty(scheduleJob.getCronExpression()), "CronExpression is null");

      TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());  
      CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);  
      if(trigger != null){  
          throw new Exception("job already exists!");  
      }
      
      // simulate job info db persist operation
      scheduleJob.setJobId(String.valueOf(QuartzJobFactory.jobList.size()+1));
      QuartzJobFactory.jobList.add(scheduleJob);
      
      JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(scheduleJob.getJobName(),scheduleJob.getJobGroup()).build();  
      jobDetail.getJobDataMap().put("scheduleJob", scheduleJob);  

      CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());  
      trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(cronScheduleBuilder).build();  

      scheduler.scheduleJob(jobDetail, trigger);  

  }
 
Example #11
Source File: ScheduleUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(Job job, CronScheduleBuilder cb)
        throws TaskException
{
    switch (job.getMisfirePolicy())
    {
        case ScheduleConstants.MISFIRE_DEFAULT:
            return cb;
        case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
            return cb.withMisfireHandlingInstructionIgnoreMisfires();
        case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
            return cb.withMisfireHandlingInstructionFireAndProceed();
        case ScheduleConstants.MISFIRE_DO_NOTHING:
            return cb.withMisfireHandlingInstructionDoNothing();
        default:
            throw new TaskException("The task misfire policy '" + job.getMisfirePolicy() + "' cannot be used in cron schedule tasks", Code.CONFIG_ERROR);
    }
}
 
Example #12
Source File: QuartzExecutor.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
public void incur(ITaskService taskService, ITaskDescriptor taskDescriptor) throws TaskException{
	
	// test if the runnable can be instantiated
	taskService.instantiateRunnableById(taskDescriptor.getIdentifiedRunnableId());
	
	String cron = taskDescriptor.getTriggerParameters().get("cron");
	CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(cron);
	
	JobKey jobKey = new JobKey(taskDescriptor.getId());
	JobDataMap jobDataMap = new JobDataMap(taskDescriptor.getRunContext());
	jobDataMap.put("taskDescriptor", taskDescriptor);
	jobDataMap.put("taskService", taskService);
	
	JobDetail jobDetail = JobBuilder.newJob(TriggerTaskJob.class).withIdentity(jobKey).build();
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(taskDescriptor.getId())
		.withSchedule(cronSchedule).usingJobData(jobDataMap).build();
	
	try {
		sched.scheduleJob(jobDetail, trigger);
	} catch (SchedulerException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
}
 
Example #13
Source File: ConfigScheduler.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
private synchronized void schedule()
{
    try
    {
        scheduler = schedulerFactory.getScheduler();

        JobDetail job = JobBuilder.newJob()
                .withIdentity(jobName)
                .ofType(ConfigSchedulerJob.class)
                .build();
        jobKey = job.getKey();
        job.getJobDataMap().put(CONFIG_SCHEDULER, this);
        CronExpression cronExpression = normalCronSchedule ? this.cronExpression : initialAndOnErrorCronExpression;
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName+"Trigger", Scheduler.DEFAULT_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
        scheduler.startDelayed(0);
        scheduler.scheduleJob(job, trigger);
        log.debug("Schedule set "+cronExpression);
    }
    catch (Exception e)
    {
        log.error("Error scheduling "+e.getMessage());
    }
}
 
Example #14
Source File: CronTriggerImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a {@link ScheduleBuilder} that is configured to produce a 
 * schedule identical to this trigger's schedule.
 * 
 * @see #getTriggerBuilder()
 */
@Override
public ScheduleBuilder<CronTrigger> getScheduleBuilder() {
    
    CronScheduleBuilder cb = CronScheduleBuilder.cronSchedule(getCronExpression())
            .inTimeZone(getTimeZone());
        
    switch(getMisfireInstruction()) {
        case MISFIRE_INSTRUCTION_DO_NOTHING : cb.withMisfireHandlingInstructionDoNothing();
        break;
        case MISFIRE_INSTRUCTION_FIRE_ONCE_NOW : cb.withMisfireHandlingInstructionFireAndProceed();
        break;
    }
    
    return cb;
}
 
Example #15
Source File: CronScheduledQueryBasedTemplateActionDefinition.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Trigger getTrigger()
{
    try
    {
        return TriggerBuilder.newTrigger()
                .withIdentity(getTriggerName(), getTriggerGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(getCronExpression()))
                .build();
    }
    // CronScheduleBuilder is throwing RuntimeException which is wrapping ParseException
    catch (final RuntimeException e)
    {
        throw new InvalidCronExpression("Invalid chron expression: n" + getCronExpression());
    }
}
 
Example #16
Source File: Db4oPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Schedules new quartz scheduler jobs for committing transactions and
 * backing up the database
 */
private void scheduleJob() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();

        // schedule commit-job
        JobDetail job = newJob(CommitJob.class).withIdentity("Commit_Transaction", SCHEDULER_GROUP).build();

        SimpleTrigger trigger = newTrigger().withIdentity("Commit_Transaction", SCHEDULER_GROUP)
                .withSchedule(repeatSecondlyForever(commitInterval)).build();

        sched.scheduleJob(job, trigger);
        logger.debug("Scheduled Commit-Job with interval {}sec.", commitInterval);

        // schedule backup-job
        JobDetail backupJob = newJob(BackupJob.class).withIdentity("Backup_DB", SCHEDULER_GROUP).build();

        CronTrigger backupTrigger = newTrigger().withIdentity("Backup_DB", SCHEDULER_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule(backupInterval)).build();

        sched.scheduleJob(backupJob, backupTrigger);
        logger.debug("Scheduled Backup-Job with cron expression '{}'", backupInterval);
    } catch (SchedulerException e) {
        logger.warn("Could not create Job: {}", e.getMessage());
    }
}
 
Example #17
Source File: AbstractQuartzScheduler.java    From deltaspike with 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 #18
Source File: SchedulerBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private void registApplicationsAndVoteCenterTask(Scheduler scheduler, String scheduleGroup) throws Exception {
	JobDetail jobDetail = JobBuilder.newJob(RegistApplicationsAndVoteCenterTask.class)
			.withIdentity(RegistApplicationsAndVoteCenterTask.class.getName(), scheduleGroup).withDescription(Config.node())
			.build();
	Trigger trigger = TriggerBuilder.newTrigger()
			.withIdentity(RegistApplicationsAndVoteCenterTask.class.getName(), scheduleGroup)
			.withSchedule(CronScheduleBuilder.cronSchedule("*/30 * * * * ?")).build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #19
Source File: SchedulerManager.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private void scheduleUpdateUserCountJob(String identifier) {
  // add another job for updating user count to Location Table.
  // 1- create a job and bind with class which is implementing Job
  // interface.
  JobDetail updateUserCountJob =
      JobBuilder.newJob(UpdateUserCountScheduler.class)
          .requestRecovery(true)
          .withDescription("Scheduler for updating user count for each geo location")
          .withIdentity("updateUserCountScheduler", identifier)
          .build();

  // 2- Create a trigger object that will define frequency of run.
  // This will run every day 2:00 AM
  Trigger updateUserCountTrigger =
      TriggerBuilder.newTrigger()
          .withIdentity("updateUserCountTrigger", identifier)
          .withSchedule(
              CronScheduleBuilder.cronSchedule(
                  PropertiesCache.getInstance().getProperty("quartz_update_user_count_timer")))
          .build();
  try {
    if (scheduler.checkExists(updateUserCountJob.getKey())) {
      scheduler.deleteJob(updateUserCountJob.getKey());
    }
    scheduler.scheduleJob(updateUserCountJob, updateUserCountTrigger);
    scheduler.start();
    ProjectLogger.log(
        "SchedulerManager:scheduleUpdateUserCountJob: UpdateUserCount schedular started",
        LoggerEnum.INFO.name());
  } catch (Exception e) {
    ProjectLogger.log(e.getMessage(), e);
  }
}
 
Example #20
Source File: SchedulerService.java    From ehousechina with Apache License 2.0 5 votes vote down vote up
public boolean setJob(String jobId,String timeStr){
		log.info(">> 添加计划任务 >> jobId >> {} >> 下次执行 >> {}",new Object[]{jobId,timeStr});
//		String jobId=getUUID();
		try {
			Scheduler scheduler = schedulerFactoryBean.getScheduler();
			scheduler.getContext().put("jobId", jobId);
			JobDetail job = JobBuilder.newJob(ProcessJob.class).withIdentity(jobId, "group1").build();
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobId, "group1").withSchedule(CronScheduleBuilder.cronSchedule(getCron(timeStr))).build();
			scheduler.scheduleJob(job, trigger);
			return true;
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return false;
	}
 
Example #21
Source File: SubscriptionCronScheduler.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
public void startJob(AbstractBean config, JobDetail job) throws SchedulerException {
  Trigger trigger = TriggerBuilder.newTrigger().withSchedule(
      CronScheduleBuilder.cronSchedule(((DetectionAlertConfigBean) config).getCronExpression())).build();
  this.scheduler.scheduleJob(job, trigger);
  LOG.info(String.format("scheduled subscription pipeline job %s", job.getKey().getName()));
}
 
Example #22
Source File: CronTriggerForm.java    From quartz-glass with Apache License 2.0 5 votes vote down vote up
public Trigger getTrigger(Trigger trigger) throws ParseException {
    fixParameters();

    return TriggerBuilder.newTrigger().forJob(trigger.getJobKey().getName(), trigger.getJobKey().getGroup())
            .withIdentity(trigger.getKey().getName(), trigger.getKey().getGroup())
            .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionIgnoreMisfires())
            .startAt(startTime).endAt(endTime)
            .usingJobData(JobDataMapUtils.fromDataMapStr(dataMap))
            .build();
}
 
Example #23
Source File: CronWindowProcessor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private void scheduleCronJob(String cronString) {
    try {
        SchedulerFactory schedFact = new StdSchedulerFactory();
        scheduler = schedFact.getScheduler();
        jobName = siddhiQueryContext.getName() + "_EventRemoverJob_" + siddhiQueryContext.generateNewId();
        JobKey jobKey = new JobKey(jobName, jobGroup);

        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
        scheduler.start();
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("windowProcessor", this);

        JobDetail job = org.quartz.JobBuilder.newJob(CronWindowProcessor.class)
                .withIdentity(jobName, jobGroup)
                .usingJobData(dataMap)
                .build();

        Trigger trigger = org.quartz.TriggerBuilder.newTrigger()
                .withIdentity("EventRemoverTrigger_" + id, jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                .build();

        scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
        log.error("Error while instantiating quartz scheduler", e);
    }
}
 
Example #24
Source File: CronTrigger.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private void scheduleCronJob(String cronString, String elementId) {
    try {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        scheduler = schedulerFactory.getScheduler();
        jobName = "TriggerJob_" + elementId;
        JobKey jobKey = new JobKey(jobName, jobGroup);

        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
        scheduler.start();
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("trigger", this);

        JobDetail job = org.quartz.JobBuilder.newJob(CronTrigger.class)
                .withIdentity(jobName, jobGroup)
                .usingJobData(dataMap)
                .build();

        org.quartz.Trigger trigger = org.quartz.TriggerBuilder.newTrigger()
                .withIdentity("TriggerJob_" + elementId, jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                .build();

        scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
        LOG.error(ExceptionUtil.getMessageWithContext(e, siddhiAppContext) +
                " Error while instantiating quartz scheduler for trigger '" + triggerDefinition.getId() + "'.", e);
    }
}
 
Example #25
Source File: CronTriggerPersistenceDelegate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public TriggerPropertyBundle loadExtendedTriggerProperties(Connection conn, TriggerKey triggerKey) throws SQLException {

        PreparedStatement ps = null;
        ResultSet rs = null;
        
        try {
            ps = conn.prepareStatement(Util.rtp(SELECT_CRON_TRIGGER, tablePrefix, schedNameLiteral));
            ps.setString(1, triggerKey.getName());
            ps.setString(2, triggerKey.getGroup());
            rs = ps.executeQuery();

            if (rs.next()) {
                String cronExpr = rs.getString(COL_CRON_EXPRESSION);
                String timeZoneId = rs.getString(COL_TIME_ZONE_ID);

                CronScheduleBuilder cb = CronScheduleBuilder.cronSchedule(cronExpr);
              
                if (timeZoneId != null) 
                    cb.inTimeZone(TimeZone.getTimeZone(timeZoneId));
                
                return new TriggerPropertyBundle(cb, null, null);
            }
            
            throw new IllegalStateException("No record found for selection of Trigger with key: '" + triggerKey + "' and statement: " + Util.rtp(SELECT_CRON_TRIGGER, tablePrefix, schedNameLiteral));
        } finally {
            Util.closeResultSet(rs);
            Util.closeStatement(ps);
        }
    }
 
Example #26
Source File: ScheduleJobService.java    From frameworkAggregate with Apache License 2.0 5 votes vote down vote up
/**
 * 更新job时间表达式
 * 
 * @param scheduleJob
 * @throws SchedulerException
 */
public void updateJobCron(ScheduleJob scheduleJob) throws SchedulerException {
	Scheduler scheduler = schedulerFactoryBean.getScheduler();
	TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
	CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
	CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
	trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
	scheduler.rescheduleJob(triggerKey, trigger);
}
 
Example #27
Source File: QuartzJobSpecScheduler.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link Trigger} from the given {@link JobSpec}
 */
private Trigger createTrigger(JobKey jobKey, JobSpec jobSpec) {
  // Build a trigger for the job with the given cron-style schedule
  return TriggerBuilder.newTrigger()
      .withIdentity("Cron for " + jobSpec.getUri())
      .forJob(jobKey)
      .withSchedule(CronScheduleBuilder.cronSchedule(
                       jobSpec.getConfig().getString(ConfigurationKeys.JOB_SCHEDULE_KEY)))
      .build();
}
 
Example #28
Source File: CallMonitor.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Reset the connection to fbox periodically.
 */
public void setupReconnectJob() {
    try {
        // String cronPattern = "0 0 0 * * ?"; //every day
        // String cronPattern = "0 * * * * ?"; //every minute
        String cronPattern = "0 0 0/2 * * ?"; // every 2 hrs
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();

        JobKey jobKey = jobKey("Reconnect", "FritzBox");
        TriggerKey triggerKey = triggerKey("Reconnect", "FritzBox");

        if (sched.checkExists(jobKey)) {
            logger.debug("reconnection job already exists");
        } else {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronPattern);

            JobDetail job = newJob(ReconnectJob.class).withIdentity(jobKey).build();

            CronTrigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            sched.scheduleJob(job, trigger);
            logger.debug("Scheduled reconnection job to FritzBox: {}", cronPattern);
        }
    } catch (SchedulerException e) {
        logger.warn("Could not create daily reconnection job", e);
    }
}
 
Example #29
Source File: JobScheduler.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link org.quartz.Trigger} from the given job configuration properties.
 */
private Trigger getTrigger(JobKey jobKey, Properties jobProps) {
  // Build a trigger for the job with the given cron-style schedule
  return TriggerBuilder.newTrigger()
      .withIdentity(jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY),
          Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_GROUP_KEY)))
      .forJob(jobKey)
      .withSchedule(CronScheduleBuilder.cronSchedule(jobProps.getProperty(ConfigurationKeys.JOB_SCHEDULE_KEY)))
      .build();
}
 
Example #30
Source File: AbstractQuartzScheduler.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private void createExpressionObserverJob(
    JobKey jobKey, UUID triggerKey, String configExpression, String cronExpression) throws SchedulerException
{
    if (!ClassDeactivationUtils.isActivated(DynamicExpressionObserverJob.class))
    {
        return;
    }

    JobKey observerJobKey =
            new JobKey(jobKey.getName() + DynamicExpressionObserverJob.OBSERVER_POSTFIX, jobKey.getGroup());

    JobDetail jobDetail  = JobBuilder.newJob(DynamicExpressionObserverJob.class)
            .usingJobData(DynamicExpressionObserverJob.CONFIG_EXPRESSION_KEY, configExpression)
            .usingJobData(DynamicExpressionObserverJob.TRIGGER_ID_KEY, triggerKey.toString())
            .usingJobData(DynamicExpressionObserverJob.ACTIVE_CRON_EXPRESSION_KEY, cronExpression)
            .withDescription("Config observer for: " + jobKey)
            .withIdentity(observerJobKey)
            .build();

    Trigger trigger = TriggerBuilder.newTrigger()
            .forJob(observerJobKey)
            .withSchedule(CronScheduleBuilder.cronSchedule(
                SchedulerBaseConfig.JobCustomization.DYNAMIC_EXPRESSION_OBSERVER_INTERVAL))
            .build();

    this.scheduler.scheduleJob(jobDetail, trigger);
}