org.quartz.CronTrigger Java Examples

The following examples show how to use org.quartz.CronTrigger. 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: MultiThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisallowConcurrent() throws Exception {
    JobDetail job1 = createJob(SingletonSleepJob.class, "job1", "group1");
    CronTrigger trigger1 = createCronTrigger("trigger1", "group1", "* * * * * ?");
    CronTrigger trigger2 = createCronTrigger("trigger2", "group2", "* * * * * ?")
            .getTriggerBuilder()
            .forJob(job1)
            .build();

    Waiter waiter = new Waiter();
    scheduler.getListenerManager().addTriggerListener(new CompleteListener(waiter), NameMatcher.triggerNameEquals(trigger1.getKey().getName()));
    scheduler.scheduleJob(job1, trigger1);
    //scheduler.scheduleJob(trigger2);

    waiter.await(6000, 2);

    assertThat(SingletonSleepJob.concurrentExecutions.get(), equalTo(0));
}
 
Example #2
Source File: DBSyncBuilder.java    From mykit-db-sync with Apache License 2.0 6 votes vote down vote up
/**
 * 启动定时任务,同步数据库的数据
 */
public void start() {
    for (int index = 0; index < jobList.size(); index++) {
        JobInfo jobInfo = jobList.get(index);
        String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
        try {
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail job = newJob(JobTask.class).withIdentity(MykitDbSyncConstants.JOB_PREFIX.concat(jobInfo.getName()), code).build();
            job.getJobDataMap().put(MykitDbSyncConstants.SRC_DB, srcDb);
            job.getJobDataMap().put(MykitDbSyncConstants.DEST_DB, destDb);
            job.getJobDataMap().put(MykitDbSyncConstants.JOB_INFO, jobInfo);
            job.getJobDataMap().put(MykitDbSyncConstants.LOG_TITLE, logTitle);
            logger.info(jobInfo.getCron());
            CronTrigger trigger = newTrigger().withIdentity(MykitDbSyncConstants.TRIGGER_PREFIX.concat(jobInfo.getName()), code).withSchedule(cronSchedule(jobInfo.getCron())).build();
            sched.scheduleJob(job, trigger);
            sched.start();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(logTitle + e.getMessage());
            logger.error(logTitle + " run failed");
            continue;
        }
    }
}
 
Example #3
Source File: JobSchedulerService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Schedule a job according cron information
 * 
 * @param job
 *            The Job to schedule
 * @param trigger
 *            The Cron trigger
 * @return Date
 */
public Date scheduleJob( JobDetail job, CronTrigger trigger )
{
    Date date = null;

    if ( _scheduler != null )
    {
        try
        {
            date = _scheduler.scheduleJob( job, trigger );
            AppLogService.info( "New job scheduled : " + job.getKey( ).getName( ) );
        }
        catch( SchedulerException e )
        {
            AppLogService.error( "Error scheduling job " + job.getKey( ).getName( ), e );
        }
    }

    return date;
}
 
Example #4
Source File: ScheduleJobServiceImpl.java    From Ffast-Java with MIT License 6 votes vote down vote up
/**
 * 项目启动时,初始化定时器
 */
@PostConstruct
public void init() {
    try {
        List<ScheduleJob> scheduleJobList = this.selectList(null);
        for (ScheduleJob scheduleJob : scheduleJobList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
            //如果不存在,则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example #5
Source File: CronTriggerDescriptor.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see org.kuali.kfs.sys.batch.TriggerDescriptor#completeTriggerDescription(org.quartz.Trigger)
 */
protected void completeTriggerDescription(Trigger trigger) {
    // prevent setting of the trigger information in test mode
    try {
        ((CronTrigger) trigger).setTimeZone(getDateTimeService().getCurrentCalendar().getTimeZone());
        if (!isTestMode()) {
            ((CronTrigger) trigger).setCronExpression(cronExpression);
        }
        else {
            ((CronTrigger) trigger).setCronExpression("0 59 23 31 12 ? 2099");
        }
    }
    catch (ParseException e) {
        throw new RuntimeException("Caught exception while trying to set the cronExpression attribute of a CronTrigger: " + getJobName(), e);
    }
}
 
Example #6
Source File: CmsTaskAct.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 开始任务调度
 * @param task 任务
 * @param taskCode 任务名称
 * @throws ParseException
 * @throws SchedulerException
 * @throws ClassNotFoundException
 */
private void startTask(CmsTask task,String taskCode) throws ParseException, SchedulerException, ClassNotFoundException{
	String cronExpress=manager.getCronExpressionFromDB(task.getId());
	System.out.println(cronExpress);
	if(cronExpress.indexOf("null")==-1){
		JobDetail jobDetail = new JobDetail();
		jobDetail.setName(taskCode);
		jobDetail.setGroup(Scheduler.DEFAULT_GROUP);
		jobDetail.setJobClass(getClassByTask(task.getJobClass()));
		//任务需要参数attr属性 
		jobDetail.setJobDataMap(getJobDataMap(task.getAttr()));
		CronTrigger cronTrigger = new CronTrigger("cron_" + taskCode,Scheduler.DEFAULT_GROUP, jobDetail.getName(),Scheduler.DEFAULT_GROUP);
		cronTrigger.setCronExpression(cronExpress);
		scheduler.scheduleJob(jobDetail, cronTrigger); 
	}
}
 
Example #7
Source File: FHTBinding.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * The user may configure this binding to update the internal clock of
 * FHT80b devices via rf command. The method takes care of scheduling this
 * job.
 */
private JobKey scheduleJob(Class<? extends Job> jobClass, String cronExpression) {
    JobKey jobKey = null;
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = JobBuilder.newJob(jobClass).withIdentity("FHT " + jobClass.getSimpleName(), "cul")
                .build();
        detail.getJobDataMap().put(FHTBinding.class.getName(), this);

        CronTrigger trigger = TriggerBuilder.newTrigger().forJob(detail)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
        jobKey = detail.getKey();
        sched.scheduleJob(detail, trigger);
    } catch (SchedulerException e) {
        logger.error("Can't schedule time update job", e);
    }
    return jobKey;
}
 
Example #8
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 #9
Source File: JobTrigger.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
/**
 * 获取正在运行的job任务
 *
 * @param scheduler scheduler
 */
public static List<JobInfo> getRunningJobs(Scheduler scheduler) throws SchedulerException {
    return Optional.ofNullable(scheduler.getCurrentlyExecutingJobs()).orElse(Collections.emptyList()).stream().map(context -> {
        JobDetail jobDetail = context.getJobDetail();
        Trigger trigger = context.getTrigger();
        JobKey jobKey = jobDetail.getKey();
        JobInfo job = new JobInfo();
        job.setJobName(jobKey.getName());
        job.setJobGroup(jobKey.getGroup());
        job.setDescription(String.format("触发器 ======== %s", trigger.getKey()));
        try {
            Trigger.TriggerState state = scheduler.getTriggerState(trigger.getKey());
            job.setJobStatus(EnumUtils.getEnum(JobStatusEnums.class, state.name()).getCode());
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                job.setCron(cronTrigger.getCronExpression());
                return job;
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return null;
    }).filter(Objects::nonNull).collect(Collectors.toList());
}
 
Example #10
Source File: JobServiceImpl.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 项目启动时,初始化定时器
 */
@PostConstruct
public void init()
{
    List<Job> jobList = jobMapper.selectJobAll();
    for (Job job : jobList)
    {
        CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, job.getJobId());
        // 如果不存在,则创建
        if (cronTrigger == null)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        else
        {
            ScheduleUtils.updateScheduleJob(scheduler, job, cronTrigger);
        }
    }
}
 
Example #11
Source File: JobServiceImpl.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 更新任务的时间表达式
 * 
 * @param job 调度信息
 */
@Override
public int updateJob(Job job)
{
    if(StrUtil.isNotEmpty(job.getUpdateBy())){
        job.setUpdateBy(job.getUpdateBy());
    }else{
        job.setUpdateBy(ShiroUtils.getLoginName());
    }
    job.setUpdateTime(new Date());
    int rows = jobMapper.updateJob(job);
    if (rows > 0)
    {
    	CronTrigger trigger = ScheduleUtils.getCronTrigger(scheduler, job.getJobId());
        ScheduleUtils.updateScheduleJob(scheduler, job, trigger);
    }
    return rows;
}
 
Example #12
Source File: QuartzUtil.java    From fixflow with Apache License 2.0 6 votes vote down vote up
/**
 * 创建复杂触发器
 * @param jobName 作业名
 * @param groupName 组名
 * @param cronExpression cron表达式
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @return
 */
public static Trigger createCronTrigger(ExecutionContext executionContext, String cronExpression,Date startTime,Date endTime) {
	
	TriggerBuilder<CronTrigger> triggerBuilder=newTrigger()
	         .withIdentity(GuidUtil.CreateGuid(), executionContext.getProcessDefinition().getId())
	         .withSchedule(cronSchedule(cronExpression));
	
	if(startTime!=null){
		triggerBuilder.startAt(startTime);
	}
	if(endTime!=null){
		triggerBuilder.endAt(endTime);
	}
	
	 CronTrigger trigger = triggerBuilder
        .build();
	return trigger;
}
 
Example #13
Source File: QuartzTaskServiceImpl.java    From mysiteforme with Apache License 2.0 6 votes vote down vote up
/**
 * 项目启动时,初始化定时器
 */
@PostConstruct
public void init(){
    EntityWrapper<QuartzTask> wrapper = new EntityWrapper<>();
    wrapper.eq("del_flag",false);
    List<QuartzTask> scheduleJobList = selectList(wrapper);
    for(QuartzTask scheduleJob : scheduleJobList){
        CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
        //如果不存在,则创建
        if(cronTrigger == null) {
            ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
        }else {
            ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
        }
    }
}
 
Example #14
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 #15
Source File: SchedulerService.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public void start() {
    try {
        SchedulerFactory sf = new StdSchedulerFactory();
        scheduler = sf.getScheduler();
        scheduler.start();

        for (Map.Entry<String, Task> entry : tasks.entrySet()) {
            Task task = entry.getValue();
            JobDetail job = newJob(SchedulerJob.class)
                .withIdentity(task.id)
                .build();

            CronTrigger trigger = newTrigger()
                .withIdentity(task.id)
                .withSchedule(cronSchedule(task.cron))
                .build();
            scheduler.scheduleJob(job, trigger);
        }
    } catch (SchedulerException e) {
        throw new ApplicationException(e);
    }
}
 
Example #16
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 #17
Source File: QssService.java    From seed with Apache License 2.0 6 votes vote down vote up
private ScheduleTask convertToScheduleTask(JobKey jobKey, Trigger trigger) throws SchedulerException {
    ScheduleTask task = new ScheduleTask();
    String[] jobname = jobKey.getName().split(":");
    task.setId(Long.parseLong(jobname[0]));
    task.setAppname(jobname[1]);
    task.setName(jobname[2]);
    //task.setGroup(jobKey.getGroup());
    //task.setDesc("触发器[" + trigger.getKey() + "]");
    //task.setStartTime(trigger.getStartTime());             //开始时间
    //task.setEndTime(trigger.getEndTime());                 //结束时间
    task.setNextFireTime(trigger.getNextFireTime());         //下次触发时间
    task.setPreviousFireTime(trigger.getPreviousFireTime()); //上次触发时间
    if(trigger instanceof CronTrigger){
        task.setCron(((CronTrigger)trigger).getCronExpression());
    }
    Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
    task.setStatus("N".equals(triggerState.name()) ? SeedConstants.QSS_STATUS_STOP : SeedConstants.QSS_STATUS_RUNNING);
    return task;
}
 
Example #18
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 #19
Source File: App.java    From database-sync with MIT License 6 votes vote down vote up
public void start(){
    for(int index = 0; index < jobList.size(); index++){
        JobInfo jobInfo = jobList.get(index);
        String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
        try{
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail job = newJob(DataTask.class).withIdentity("job-" + jobInfo.getName(), code).build();
            job.getJobDataMap().put("srcDb", srcDb);
            job.getJobDataMap().put("destDb", destDb);
            job.getJobDataMap().put("jobInfo", jobInfo);
            job.getJobDataMap().put("logTitle", logTitle);
            logger.info(jobInfo.getCron());
            CronTrigger trigger = newTrigger()
                            .withIdentity("trigger-" +  jobInfo.getName(), code)
                            .withSchedule(cronSchedule(jobInfo.getCron())).build();
            sched.scheduleJob(job, trigger);
            sched.start();  
        }catch(Exception e){
            logger.info(logTitle + e.getMessage());
            logger.info(logTitle + " run failed");
            continue;
        }
    }
}
 
Example #20
Source File: CronSchedulerImpl.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<CrontabEntry> getSchedule(IJobKey jobKey) throws IllegalStateException {
  requireNonNull(jobKey);

  try {
    return Optional.of(Iterables.getOnlyElement(
        FluentIterable.from(scheduler.getTriggersOfJob(jobKey(jobKey)))
            .filter(CronTrigger.class)
            .transform(Quartz::crontabEntry)));
  } catch (SchedulerException e) {
    LOG.error(
        "Error reading job " + JobKeys.canonicalString(jobKey) + " cronExpression Quartz: " + e,
        e);
    return Optional.empty();
  }
}
 
Example #21
Source File: CronTriggerPersistenceDelegate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public int updateExtendedTriggerProperties(Connection conn, OperableTrigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException {

        CronTrigger cronTrigger = (CronTrigger)trigger;
        
        PreparedStatement ps = null;

        try {
            ps = conn.prepareStatement(Util.rtp(UPDATE_CRON_TRIGGER, tablePrefix, schedNameLiteral));
            ps.setString(1, cronTrigger.getCronExpression());
            ps.setString(2, cronTrigger.getTimeZone().getID());
            ps.setString(3, trigger.getKey().getName());
            ps.setString(4, trigger.getKey().getGroup());
            
            return ps.executeUpdate();
        } finally {
            Util.closeStatement(ps);
        }
    }
 
Example #22
Source File: SchedulerMainService.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 스케줄러 Job등록
 * @throws Exception
 * @return void
 */
public void JobRegist() throws Exception {
	Class<?> c = null;
	// 등록할 스케줄 정보 설정
	setSchList();

	for (int j = 0; j < schDTO.length; j++) {
		try {
			c = Class.forName(schDTO[j].getTask_class());

			jobDetail = new JobDetail(schDTO[j].getTask_id(), schDTO[j].getTask_group_id(), c);
			trigger = new CronTrigger(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());

			trigger.setCronExpression(schDTO[j].getTask_expression());
			scheduler.scheduleJob(jobDetail, trigger);
		} catch (Exception e) {
			throw e;
		}
	}
}
 
Example #23
Source File: CronTriggerSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static CompositeData toCompositeData(CronTrigger trigger) {
    try {
        return new CompositeDataSupport(COMPOSITE_TYPE, ITEM_NAMES,
                new Object[] {
                        trigger.getCronExpression(),
                        trigger.getTimeZone(),
                        trigger.getKey().getName(),
                        trigger.getKey().getGroup(),
                        trigger.getJobKey().getName(),
                        trigger.getJobKey().getGroup(),
                        trigger.getDescription(),
                        JobDataMapSupport.toTabularData(trigger
                                .getJobDataMap()),
                        trigger.getCalendarName(),
                        ((OperableTrigger)trigger).getFireInstanceId(),
                        trigger.getMisfireInstruction(),
                        trigger.getPriority(), trigger.getStartTime(),
                        trigger.getEndTime(), trigger.getNextFireTime(),
                        trigger.getPreviousFireTime(),
                        trigger.getFinalFireTime() });
    } catch (OpenDataException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
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 #25
Source File: SingleThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void testMisfireListener() throws Exception {
    final String jobName = "oneJob";
    JobDetail jobDetail = createJob(TestJob.class, jobName, "oneGroup");

    final String triggerName = "trigger1";
    final String everySecond = "* * * * * ?";
    CronTrigger trigger = createCronTrigger(triggerName, "oneGroup", everySecond);


    JobDetail sleepJob = createJob(SleepJob.class, "sleepJob", "twoGroup");
    CronTrigger sleepTrigger = createCronTrigger("sleepTrigger", "twoGroup", everySecond);
    Waiter waiter = new Waiter();
    scheduler.scheduleJob(sleepJob, sleepTrigger);
    scheduler.scheduleJob(jobDetail, trigger);

    scheduler.getListenerManager().addTriggerListener(new MisfireListener(waiter), NameMatcher.triggerNameEquals(triggerName));

    // wait for MisfireListener.triggerMisfired() to be called
    waiter.await(2500);
}
 
Example #26
Source File: StdJDBCDelegate.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Insert the cron trigger data.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param trigger
 *          the trigger to insert
 * @return the number of rows inserted
 */
public int insertCronTrigger(Connection conn, CronTrigger trigger)
    throws SQLException {
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(INSERT_CRON_TRIGGER));
        ps.setString(1, trigger.getName());
        ps.setString(2, trigger.getGroup());
        ps.setString(3, trigger.getCronExpression());
        ps.setString(4, trigger.getTimeZone().getID());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}
 
Example #27
Source File: StdJDBCDelegate.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Update the cron trigger data.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param trigger
 *          the trigger to insert
 * @return the number of rows updated
 */
public int updateCronTrigger(Connection conn, CronTrigger trigger)
    throws SQLException {
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_CRON_TRIGGER));
        ps.setString(1, trigger.getCronExpression());
        ps.setString(2, trigger.getName());
        ps.setString(3, trigger.getGroup());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}
 
Example #28
Source File: RepositoryContainerTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testLargeContentRequest() throws Exception
{
    authenticationComponent.setCurrentUser(USER_ONE);
    
    // create the 5 mb size buffer of zero bytes
    byte[] content = new byte[5 * 1024 * 1024];
    Arrays.fill(content, (byte)0);
    
    // chek that we can upload file larger than 4 mb
    Response response = sendRequest(new PutRequest("/test/largecontenttest", content, "text/plain"), STATUS_OK);
    assertEquals(SUCCESS, response.getContentAsString());
    
    // trigger the webscript temp folder cleaner job
    CronTrigger webscriptsTempFileCleanerJobTrigger = (CronTrigger) getServer().getApplicationContext().getBean("webscripts.tempFileCleanerTrigger");

    Scheduler scheduler = (Scheduler) getServer().getApplicationContext().getBean("schedulerFactory");

    scheduler.triggerJob(webscriptsTempFileCleanerJobTrigger.getJobKey());

    // check that we still can upload file larger than 4 mb, i.e. ensure that cleaner has not deleted temp folder
    response = sendRequest(new PutRequest("/test/largecontenttest", content, "text/plain"), STATUS_OK);
    assertEquals(SUCCESS, response.getContentAsString());
}
 
Example #29
Source File: DynamicTask.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 更新定时任务的触发表达式
 * 
 * @param triggerName
 *            触发器名字
 * @param start
 *            触发表达式
 * @return 成功则返回true,否则返回false
 */
public boolean startOrStop(String triggerName,
		boolean start) {
	try {
		CronTrigger trigger = (CronTrigger) getTrigger(triggerName,
				Scheduler.DEFAULT_GROUP);
		if(start){
			schedulerFactory.resumeTrigger(trigger.getName(), trigger.getGroup());
			logger.info("trigger the start successfully!!");
		}else{
			schedulerFactory.pauseTrigger(trigger.getName(), trigger.getGroup());
			logger.info("trigger the pause successfully!!");
		}
		return true;
	}  catch (SchedulerException e) {
		logger.error("Fail to reschedule. " + e);
		return false;
	}
}
 
Example #30
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);  

  }