Java 类org.quartz.SimpleTrigger 实例源码

项目:spring-boot-quartz-demo    文件:JobServiceImpl.java   
/**
 * Schedule a job by jobName at given date.
 */
@Override
public boolean scheduleCronJob(String jobName, Class<? extends QuartzJobBean> jobClass, Date date, String cronExpression) {
    System.out.println("Request received to scheduleJob");

    String jobKey = jobName;
    String groupKey = "SampleGroup";    
    String triggerKey = jobName;        

    JobDetail jobDetail = JobUtil.createJob(jobClass, false, context, jobKey, groupKey);

    System.out.println("creating trigger for key :"+jobKey + " at date :"+date);
    Trigger cronTriggerBean = JobUtil.createCronTrigger(triggerKey, date, cronExpression, SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

    try {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        Date dt = scheduler.scheduleJob(jobDetail, cronTriggerBean);
        System.out.println("Job with key jobKey :"+jobKey+ " and group :"+groupKey+ " scheduled successfully for date :"+dt);
        return true;
    } catch (SchedulerException e) {
        System.out.println("SchedulerException while scheduling job with key :"+jobKey + " message :"+e.getMessage());
        e.printStackTrace();
    }

    return false;
}
项目:spring-boot-quartz-demo    文件:JobServiceImpl.java   
/**
 * Update one time scheduled job.
 */
@Override
public boolean updateOneTimeJob(String jobName, Date date) {
    System.out.println("Request received for updating one time job.");

    String jobKey = jobName;

    System.out.println("Parameters received for updating one time job : jobKey :"+jobKey + ", date: "+date);
    try {
        //Trigger newTrigger = JobUtil.createSingleTrigger(jobKey, date, SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
        Trigger newTrigger = JobUtil.createSingleTrigger(jobKey, date, SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

        Date dt = schedulerFactoryBean.getScheduler().rescheduleJob(TriggerKey.triggerKey(jobKey), newTrigger);
        System.out.println("Trigger associated with jobKey :"+jobKey+ " rescheduled successfully for date :"+dt);
        return true;
    } catch ( Exception e ) {
        System.out.println("SchedulerException while updating one time job with key :"+jobKey + " message :"+e.getMessage());
        e.printStackTrace();
        return false;
    }
}
项目:spring-boot-quartz-demo    文件:JobServiceImpl.java   
/**
 * Update scheduled cron job.
 */
@Override
public boolean updateCronJob(String jobName, Date date, String cronExpression) {
    System.out.println("Request received for updating cron job.");

    String jobKey = jobName;

    System.out.println("Parameters received for updating cron job : jobKey :"+jobKey + ", date: "+date);
    try {
        //Trigger newTrigger = JobUtil.createSingleTrigger(jobKey, date, SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
        Trigger newTrigger = JobUtil.createCronTrigger(jobKey, date, cronExpression, SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

        Date dt = schedulerFactoryBean.getScheduler().rescheduleJob(TriggerKey.triggerKey(jobKey), newTrigger);
        System.out.println("Trigger associated with jobKey :"+jobKey+ " rescheduled successfully for date :"+dt);
        return true;
    } catch ( Exception e ) {
        System.out.println("SchedulerException while updating cron job with key :"+jobKey + " message :"+e.getMessage());
        e.printStackTrace();
        return false;
    }
}
项目:freemoz    文件:JobService.java   
private void startIndexerJob() throws SchedulerException {
    Scheduler scheduler = Singleton.getScheduler();
    // Setup the indexer which runs forever indexing
    JobDetail job = newJob(IndexJob.class)
            .withIdentity("indexjob")
            .build();

    SimpleTrigger trigger = newTrigger()
            .withIdentity("indexerjob")
            .withSchedule(simpleSchedule()
                    .withIntervalInHours(24)
                    .repeatForever()
            )
            .build();

    scheduler.scheduleJob(job, trigger);
    scheduler.start();
}
项目:lams    文件:SimpleTriggerPersistenceDelegate.java   
public int insertExtendedTriggerProperties(Connection conn, OperableTrigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException {

        SimpleTrigger simpleTrigger = (SimpleTrigger)trigger;

        PreparedStatement ps = null;

        try {
            ps = conn.prepareStatement(Util.rtp(INSERT_SIMPLE_TRIGGER, tablePrefix, schedNameLiteral));
            ps.setString(1, trigger.getKey().getName());
            ps.setString(2, trigger.getKey().getGroup());
            ps.setInt(3, simpleTrigger.getRepeatCount());
            ps.setBigDecimal(4, new BigDecimal(String.valueOf(simpleTrigger.getRepeatInterval())));
            ps.setInt(5, simpleTrigger.getTimesTriggered());

            return ps.executeUpdate();
        } finally {
            Util.closeStatement(ps);
        }
    }
项目:lams    文件:SimpleTriggerPersistenceDelegate.java   
public int updateExtendedTriggerProperties(Connection conn, OperableTrigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException {

        SimpleTrigger simpleTrigger = (SimpleTrigger)trigger;

        PreparedStatement ps = null;

        try {
            ps = conn.prepareStatement(Util.rtp(UPDATE_SIMPLE_TRIGGER, tablePrefix, schedNameLiteral));

            ps.setInt(1, simpleTrigger.getRepeatCount());
            ps.setBigDecimal(2, new BigDecimal(String.valueOf(simpleTrigger.getRepeatInterval())));
            ps.setInt(3, simpleTrigger.getTimesTriggered());
            ps.setString(4, simpleTrigger.getKey().getName());
            ps.setString(5, simpleTrigger.getKey().getGroup());

            return ps.executeUpdate();
        } finally {
            Util.closeStatement(ps);
        }
    }
项目:lams    文件:SimpleTriggerImpl.java   
/**
 * Get a {@link ScheduleBuilder} that is configured to produce a 
 * schedule identical to this trigger's schedule.
 * 
 * @see #getTriggerBuilder()
 */
@Override
public ScheduleBuilder<SimpleTrigger> getScheduleBuilder() {

    SimpleScheduleBuilder sb = SimpleScheduleBuilder.simpleSchedule()
    .withIntervalInMilliseconds(getRepeatInterval())
    .withRepeatCount(getRepeatCount());

    switch(getMisfireInstruction()) {
        case MISFIRE_INSTRUCTION_FIRE_NOW : sb.withMisfireHandlingInstructionFireNow();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT : sb.withMisfireHandlingInstructionNextWithExistingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT : sb.withMisfireHandlingInstructionNextWithRemainingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT : sb.withMisfireHandlingInstructionNowWithExistingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT : sb.withMisfireHandlingInstructionNowWithRemainingCount();
        break;
    }

    return sb;
}
项目:lams    文件:SimpleTriggerSupport.java   
public static CompositeData toCompositeData(SimpleTrigger trigger) {
    try {
        return new CompositeDataSupport(COMPOSITE_TYPE, ITEM_NAMES,
                new Object[] {
                        trigger.getRepeatCount(),
                        trigger.getRepeatInterval(),
                        trigger.getTimesTriggered(),
                        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);
    }
}
项目:asura    文件:StdJDBCDelegate.java   
/**
 * <p>
 * Insert the simple trigger data.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param trigger
 *          the trigger to insert
 * @return the number of rows inserted
 */
public int insertSimpleTrigger(Connection conn, SimpleTrigger trigger)
    throws SQLException {
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(INSERT_SIMPLE_TRIGGER));
        ps.setString(1, trigger.getName());
        ps.setString(2, trigger.getGroup());
        ps.setInt(3, trigger.getRepeatCount());
        ps.setBigDecimal(4, new BigDecimal(String.valueOf(trigger
                .getRepeatInterval())));
        ps.setInt(5, trigger.getTimesTriggered());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}
项目:asura    文件:StdJDBCDelegate.java   
/**
 * <p>
 * Update the simple trigger data.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param trigger
 *          the trigger to insert
 * @return the number of rows updated
 */
public int updateSimpleTrigger(Connection conn, SimpleTrigger trigger)
    throws SQLException {
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_SIMPLE_TRIGGER));

        ps.setInt(1, trigger.getRepeatCount());
        ps.setBigDecimal(2, new BigDecimal(String.valueOf(trigger
                .getRepeatInterval())));
        ps.setInt(3, trigger.getTimesTriggered());
        ps.setString(4, trigger.getName());
        ps.setString(5, trigger.getGroup());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}
项目:webside    文件:QuartzSessionValidationScheduler.java   
public void enableSessionValidation() {  
    if (log.isDebugEnabled()) {  
        log.debug("Scheduling session validation job using Quartz with session validation interval of ["  
                + this.sessionValidationInterval + "]ms...");  
    }  

    try {  
        SimpleTrigger trigger = TriggerBuilder.newTrigger().startNow().withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP)  
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(sessionValidationInterval))  
                .build(); 

        JobDetail detail = JobBuilder.newJob(QuartzSessionValidationJob.class)  
                .withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP).build();  
        detail.getJobDataMap().put(SESSION_MANAGER_KEY, this.sessionManager);  
        Scheduler scheduler = getScheduler();  

        scheduler.scheduleJob(detail, trigger);  
        if (this.schedulerImplicitlyCreated) {  
            scheduler.start();  
            if (log.isDebugEnabled()) {  
                log.debug("Successfully started implicitly created Quartz Scheduler instance.");  
            }  
        }  
        this.enabled = true;  

        if (log.isDebugEnabled())  
            log.debug("Session validation job successfully scheduled with Quartz.");  
    } catch (SchedulerException e) {  
        if (log.isErrorEnabled())  
            log.error("Error starting the Quartz session validation job.  Session validation may not occur.", e);  
    }  
}
项目:jaffa-framework    文件:TriggerHelper.java   
/** Creates a SimpleTrigger with an interval computed from the hours, minutes and seconds.
 */
private static AbstractTrigger<?> createTrigger(ScheduledTask task, Recurrence.Often recurrence) throws FrameworkException, ApplicationExceptions {
    // Compute the repeatInterval for the SimpleTrigger in milliseconds
    long repeatInterval = 0;
    if (recurrence.getHours() != null)
        repeatInterval += recurrence.getHours() * 60 * 60 * 1000;
    if (recurrence.getMinutes() != null)
        repeatInterval += recurrence.getMinutes() * 60 * 1000;
    if (recurrence.getSeconds() != null)
        repeatInterval += recurrence.getSeconds() * 1000;

    SimpleTriggerImpl trigger = new SimpleTriggerImpl();
    if (repeatInterval > 0) {
        trigger.setRepeatInterval(repeatInterval);
        trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    }
    return trigger;
}
项目:openbravo-brazil    文件:OBScheduler.java   
private static final Trigger makeIntervalTrigger(String type, String interval,
    String repititions) throws ParseException {
  try {
    final int i = Integer.parseInt(interval);
    int r = SimpleTrigger.REPEAT_INDEFINITELY;
    if (!repititions.trim().equals("")) {
      r = Integer.parseInt(repititions);
    }
    if (type.equals(FREQUENCY_SECONDLY)) {
      return TriggerUtils.makeSecondlyTrigger(i, r);

    } else if (type.equals(FREQUENCY_MINUTELY)) {
      return TriggerUtils.makeMinutelyTrigger(i, r);

    } else if (type.equals(FREQUENCY_HOURLY)) {
      return TriggerUtils.makeHourlyTrigger(i, r);
    }
    return null;

  } catch (final NumberFormatException e) {
    throw new ParseException("Invalid interval or repitition value.", -1);
  }
}
项目:data    文件:SchedulerServiceImpl.java   
@Override
public void schedule(String name, Date startTime, Date endTime,
        int repeatCount, long repeatInterval) {
    if (name == null || name.trim().equals("")) {
        name = UUID.randomUUID().toString();
    }
    try {
        scheduler.addJob(jobDetail, true);

        SimpleTrigger simpleTrigger = new SimpleTrigger(name,
                Scheduler.DEFAULT_GROUP, jobDetail.getName(),
                Scheduler.DEFAULT_GROUP, startTime, endTime, repeatCount,
                repeatInterval);
        scheduler.scheduleJob(simpleTrigger);
        scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP,
                simpleTrigger);
    } catch (SchedulerException e) {
        log.error(e);
        throw new RuntimeException(e);
    }
}
项目:Unicorn    文件:EventAdapter.java   
public void start(final long interval) {
    try {
        // Grab the Scheduler instance from the Factory
        final org.quartz.Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // define the job and tie it to our NokiaHereAdapter class
        final JobDetail jd = new JobDetail(this.name, Scheduler.DEFAULT_GROUP, AdapterJob.class);

        // triggers all 120 seconds the execution of execution, never ends
        final SimpleTrigger simpleTrigger = new SimpleTrigger(this.name, Scheduler.DEFAULT_GROUP, new Date(), null, SimpleTrigger.REPEAT_INDEFINITELY, interval * 1000);

        // Tell quartz to schedule the job using our trigger
        scheduler.scheduleJob(jd, simpleTrigger);
        scheduler.start();
    } catch (final SchedulerException se) {
        se.printStackTrace();
    }
}
项目:Camel    文件:QuartzEndpointConfigureTest.java   
@Test
public void testConfigureGroupAndName() throws Exception {
    QuartzEndpoint endpoint = resolveMandatoryEndpoint("quartz2://myGroup/myName?trigger.repeatCount=3&trigger.repeatInterval=1000");

    Scheduler scheduler = endpoint.getComponent().getScheduler();
    TriggerKey triggerKey = endpoint.getTriggerKey();
    Trigger trigger = scheduler.getTrigger(triggerKey);
    JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(triggerKey.getName(), triggerKey.getGroup()));

    assertEquals("getName()", "myName", triggerKey.getName());
    assertEquals("getGroup()", "myGroup", triggerKey.getGroup());
    assertEquals("getJobName", "myName", jobDetail.getKey().getName());
    assertEquals("getJobGroup", "myGroup", jobDetail.getKey().getGroup());

    SimpleTrigger simpleTrigger = assertIsInstanceOf(SimpleTrigger.class, trigger);
    assertEquals("getRepeatCount()", 3, simpleTrigger.getRepeatCount());
}
项目:Camel    文件:QuartzSimpleRouteTest.java   
@Test
public void testQuartzCronRoute() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMinimumMessageCount(3);

    assertMockEndpointsSatisfied();
    Trigger trigger = mock.getReceivedExchanges().get(0).getIn().getHeader("trigger", Trigger.class);
    Assert.assertThat(trigger instanceof SimpleTrigger, CoreMatchers.is(true));

    JobDetail detail = mock.getReceivedExchanges().get(0).getIn().getHeader("jobDetail", JobDetail.class);
    Assert.assertThat(detail.getJobClass().equals(CamelJob.class), CoreMatchers.is(true));

    Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_TYPE).equals("simple"), CoreMatchers.is(true));
    Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_SIMPLE_REPEAT_COUNTER).equals(-1), CoreMatchers.is(true));
    Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_SIMPLE_REPEAT_INTERVAL).equals(2000L), CoreMatchers.is(true));
}
项目:kc-rice    文件:DefaultExceptionServiceImpl.java   
public void scheduleExecution(Throwable throwable, PersistedMessageBO message, String description) throws Exception {
    KSBServiceLocator.getMessageQueueService().delete(message);
       PersistedMessageBO messageCopy = message.copy();
    Scheduler scheduler = KSBServiceLocator.getScheduler();
    JobDataMap jobData = new JobDataMap();
    jobData.put(MessageServiceExecutorJob.MESSAGE_KEY, messageCopy);
    JobDetail jobDetail = new JobDetail("Exception_Message_Job " + Math.random(), "Exception Messaging",
        MessageServiceExecutorJob.class);
    jobDetail.setJobDataMap(jobData);
    if (!StringUtils.isBlank(description)) {
        jobDetail.setDescription(description);
    }
    jobDetail.addJobListener(MessageServiceExecutorJobListener.NAME);
    Trigger trigger = new SimpleTrigger("Exception_Message_Trigger " + Math.random(), "Exception Messaging", messageCopy
        .getQueueDate());
    trigger.setJobDataMap(jobData);// 1.6 bug required or derby will choke
    scheduler.scheduleJob(jobDetail, trigger);    
}
项目:openhab-hdl    文件:GCalPersistenceService.java   
/**
 * Schedules new quartz scheduler job for uploading calendar entries to Google
 */
private void scheduleUploadJob() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        JobDetail job = newJob(SynchronizationJob.class)
            .withIdentity("Upload_GCal-Entries", GCAL_SCHEDULER_GROUP)
            .build();

        SimpleTrigger trigger = newTrigger()
            .withIdentity("Upload_GCal-Entries", GCAL_SCHEDULER_GROUP)
            .withSchedule(repeatSecondlyForever(uploadInterval))
            .build();

        sched.scheduleJob(job, trigger);
        logger.debug("Scheduled Google Calendar Upload-Job with interval '{}'", uploadInterval);
    } catch (SchedulerException e) {
        logger.warn("Could not create Google Calendar Upload-Job: {}", e.getMessage());
    }       
}
项目:openhab-hdl    文件:MapDBPersistenceService.java   
/**
 * 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);

    } catch (SchedulerException e) {
        logger.warn("Could not create Job: {}", e.getMessage());
    }
}
项目:openhab-hdl    文件:ConfigDispatcher.java   
/**
 * Schedules a quartz job which is triggered every minute.
 */
public static void scheduleRefreshJob() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        JobDetail job = newJob(RefreshJob.class)
            .withIdentity(REFRESH_JOB_KEY)
            .build();

        SimpleTrigger trigger = newTrigger()
            .withIdentity(REFRESH_TRIGGER_KEY)
            .withSchedule(repeatSecondlyForever(refreshInterval))
            .build();

        sched.scheduleJob(job, trigger);
        logger.debug("Scheduled refresh job '{}' in DefaulScheduler", job.getKey());
    } catch (SchedulerException e) {
        logger.warn("Could not schedule refresh job: {}", e.getMessage());
    }
}
项目:openhab-hdl    文件:ConfigDispatcher.java   
/**
 * Reschedules a quartz job which is triggered every minute.
 */
public static void rescheduleRefreshJob() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();

        SimpleTrigger trigger = newTrigger()
            .withIdentity(REFRESH_TRIGGER_KEY)
            .withSchedule(repeatSecondlyForever(refreshInterval))
            .build();

        sched.rescheduleJob(REFRESH_TRIGGER_KEY, trigger);
        logger.debug("Rescheduled refresh job '{}' in DefaulScheduler", REFRESH_TRIGGER_KEY);
    } catch (SchedulerException e) {
        logger.warn("Could not reschedule refresh job: {}", e.getMessage());
    }
}
项目:motech    文件:SchedulableJobBuilder.java   
private static SchedulableJob buildRepeatingSchedulableJob(Trigger trigger, JobDataMap dataMap) {
    RepeatingSchedulableJob job = new RepeatingSchedulableJob();
    long interval;

    if (trigger instanceof CalendarIntervalTrigger) {
        CalendarIntervalTrigger calendarTrigger = (CalendarIntervalTrigger) trigger;
        interval = calendarTrigger.getRepeatInterval();
    } else {
        SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
        job.setRepeatCount(simpleTrigger.getRepeatCount());
        interval = simpleTrigger.getRepeatInterval() / SECOND;
    }

    job.setEndDate(getEndDate(trigger));
    job.setRepeatIntervalInSeconds((int) interval);
    job.setIgnorePastFiresAtStart(dataMap.getBoolean(IGNORE_PAST_FIRES_AT_START));
    job.setUseOriginalFireTimeAfterMisfire(dataMap.getBoolean(USE_ORIGINAL_FIRE_TIME_AFTER_MISFIRE));

    return job;
}
项目:motech    文件:CronJobSimpleExpressionBuilderTest.java   
@Test
public void shouldScheduleJobEverySevenDays() {
    SimpleTrigger trigger = newTrigger()
            .withIdentity(triggerKey("triggerName", "groupName"))
            .startNow()
            .withSchedule(simpleSchedule()
                .withIntervalInHours(7 * 24)
                .repeatForever())
            .build();

    LocalDate today = DateUtil.today();
    Date yesterday = today.plusDays(-1).toDate();

    Date firstFireTime = trigger.getFireTimeAfter(yesterday);
    Date secondFireTime = trigger.getFireTimeAfter(firstFireTime);
    Date thirdFireTime = trigger.getFireTimeAfter(secondFireTime);

    assertEquals(Duration.standardDays(7).getMillis(), secondFireTime.getTime() - firstFireTime.getTime());
    assertEquals(Duration.standardDays(7).getMillis(), thirdFireTime.getTime() - secondFireTime.getTime());
}
项目:quartz    文件:QuartzUtils.java   
public void addNewDeviceJob(JobDetail detail) {
    // Scheduler scheduler = (Scheduler) ac.getBean("schedulerFactoryBean");
    SimpleTrigger trigger1 = newTrigger()
            .withIdentity("trigger1", "group1")
            .startAt(new Date())
            .withSchedule(
                    simpleSchedule().withIntervalInSeconds(10)
                            .withRepeatCount(0)).build();

    detail.getJobDataMap().put("xxxx", "######  绿   #####");

    Date scheduleTime1 = null;
    try {
        scheduleTime1 = scheduler.scheduleJob(detail, trigger1);
    } catch (SchedulerException e) {

        e.printStackTrace();
    }
    System.out.println(detail.getKey().getName() + " 将在 : " + scheduleTime1
            + " 执行, 并重复 : " + trigger1.getRepeatCount() + " 次, 每次间隔   "
            + trigger1.getRepeatInterval() / 1000 + " 秒");

}
项目:pfm-mustic9    文件:MasterSOASchedulerServlet.java   
/**
 * Init servlet
 */
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {
        schedFact = new StdSchedulerFactory("soa_quartz.properties");
        sched = schedFact.getScheduler();
        System.out.println(this.getClass().getName() + " started");
        sched.start();

        // Create Master Dispatch job
        JobDetail jd = new JobDetail(MASTER_JOB_NAME, GROUP_NAME, MasterSOAJob.class);
        int repeatInterval = Integer.parseInt(getInitParameter("TRIGGER_REPEATINTERVAL"));
        System.out.println(this.getClass().getName() + " Repeat interval for " + MASTER_JOB_NAME + ": " + repeatInterval + " milliseconds");
        SimpleTrigger simpleTrigger = new SimpleTrigger(MASTER_TRIGGER_NAME, GROUP_NAME, SimpleTrigger.REPEAT_INDEFINITELY, repeatInterval);
        System.out.println(this.getClass().getName() + " Scheduling Job " + MASTER_JOB_NAME);
        sched.scheduleJob(jd, simpleTrigger);
        System.out.println(this.getClass().getName() + " Job " + MASTER_JOB_NAME + " scheduled");

    } catch (Exception e) {
        System.err.println(this.getClass().getName() + " " + e.getLocalizedMessage());
        e.printStackTrace(System.err);
    }
}
项目:quartz-redis-jobstore    文件:SimpleTriggerMixinTest.java   
@Test
public void serialization(){
    SimpleTrigger trigger = TriggerBuilder.newTrigger()
            .forJob("testJob", "testGroup")
            .withIdentity("testTrigger", "testTriggerGroup")
            .usingJobData("timeout", 5)
            .withDescription("A description!")
            .withSchedule(SimpleScheduleBuilder.repeatHourlyForever())
            .build();

    Map<String, String> triggerMap = mapper.convertValue(trigger, new TypeReference<HashMap<String, String>>() {});

    assertThat(triggerMap, hasKey("name"));
    assertEquals("testTrigger", triggerMap.get("name"));
    assertThat(triggerMap, hasKey("group"));
    assertEquals("testTriggerGroup", triggerMap.get("group"));
    assertThat(triggerMap, hasKey("jobName"));
    assertEquals("testJob", triggerMap.get("jobName"));

    SimpleTriggerImpl simpleTrigger = mapper.convertValue(triggerMap, SimpleTriggerImpl.class);

    assertEquals(trigger.getKey().getName(), simpleTrigger.getKey().getName());
    assertEquals(trigger.getKey().getGroup(), simpleTrigger.getKey().getGroup());
    assertEquals(trigger.getStartTime(), simpleTrigger.getStartTime());
    assertEquals(trigger.getRepeatInterval(), simpleTrigger.getRepeatInterval());
}
项目:SelfSoftShop    文件:JobServiceImpl.java   
public void buildIndexHtml() {
    try {
        SimpleTrigger simpleTrigger = new SimpleTrigger();
        simpleTrigger.setName(BuildIndexHtmlJob.TRIGGER_NAME);
        simpleTrigger.setGroup(BuildIndexHtmlJob.GROUP_NAME);
        simpleTrigger.setJobName(BuildIndexHtmlJob.JOB_NAME);
        simpleTrigger.setJobGroup(BuildIndexHtmlJob.GROUP_NAME);
        simpleTrigger.setStartTime(DateUtils.addSeconds(new Date(), SettingUtil.getSetting().getBuildHtmlDelayTime()));
        simpleTrigger.setRepeatCount(0);
        simpleTrigger.setRepeatInterval(60);

        JobDetail jobDetail = scheduler.getJobDetail(BuildIndexHtmlJob.JOB_NAME, BuildIndexHtmlJob.GROUP_NAME);
        if (jobDetail != null) {
            scheduler.rescheduleJob(BuildIndexHtmlJob.TRIGGER_NAME, BuildIndexHtmlJob.GROUP_NAME, simpleTrigger);
        } else {
            jobDetail = new JobDetail(BuildIndexHtmlJob.JOB_NAME, BuildIndexHtmlJob.GROUP_NAME, BuildIndexHtmlJob.class);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
        }

        if (scheduler.isShutdown()) {
            scheduler.start();
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
项目:SelfSoftShop    文件:JobServiceImpl.java   
public void buildLoginHtml() {
    try {
        SimpleTrigger simpleTrigger = new SimpleTrigger();
        simpleTrigger.setName(BuildLoginHtmlJob.TRIGGER_NAME);
        simpleTrigger.setGroup(BuildLoginHtmlJob.GROUP_NAME);
        simpleTrigger.setJobName(BuildLoginHtmlJob.JOB_NAME);
        simpleTrigger.setJobGroup(BuildLoginHtmlJob.GROUP_NAME);
        simpleTrigger.setStartTime(DateUtils.addSeconds(new Date(), SettingUtil.getSetting().getBuildHtmlDelayTime()));
        simpleTrigger.setRepeatCount(0);
        simpleTrigger.setRepeatInterval(60);

        JobDetail jobDetail = scheduler.getJobDetail(BuildLoginHtmlJob.JOB_NAME, BuildLoginHtmlJob.GROUP_NAME);
        if (jobDetail != null) {
            scheduler.rescheduleJob(BuildLoginHtmlJob.TRIGGER_NAME, BuildLoginHtmlJob.GROUP_NAME, simpleTrigger);
        } else {
            jobDetail = new JobDetail(BuildLoginHtmlJob.JOB_NAME, BuildLoginHtmlJob.GROUP_NAME, BuildLoginHtmlJob.class);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
        }

        if (scheduler.isShutdown()) {
            scheduler.start();
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
项目:SelfSoftShop    文件:JobServiceImpl.java   
public void buildRegisterAgreementHtml() {
    try {
        SimpleTrigger simpleTrigger = new SimpleTrigger();
        simpleTrigger.setName(BuildRegisterAgreementHtmlJob.TRIGGER_NAME);
        simpleTrigger.setGroup(BuildRegisterAgreementHtmlJob.GROUP_NAME);
        simpleTrigger.setJobName(BuildRegisterAgreementHtmlJob.JOB_NAME);
        simpleTrigger.setJobGroup(BuildRegisterAgreementHtmlJob.GROUP_NAME);
        simpleTrigger.setStartTime(DateUtils.addSeconds(new Date(), SettingUtil.getSetting().getBuildHtmlDelayTime()));
        simpleTrigger.setRepeatCount(0);
        simpleTrigger.setRepeatInterval(60);

        JobDetail jobDetail = scheduler.getJobDetail(BuildRegisterAgreementHtmlJob.JOB_NAME, BuildRegisterAgreementHtmlJob.GROUP_NAME);
        if (jobDetail != null) {
            scheduler.rescheduleJob(BuildRegisterAgreementHtmlJob.TRIGGER_NAME, BuildRegisterAgreementHtmlJob.GROUP_NAME, simpleTrigger);
        } else {
            jobDetail = new JobDetail(BuildRegisterAgreementHtmlJob.JOB_NAME, BuildRegisterAgreementHtmlJob.GROUP_NAME, BuildRegisterAgreementHtmlJob.class);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
        }

        if (scheduler.isShutdown()) {
            scheduler.start();
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
项目:SelfSoftShop    文件:JobServiceImpl.java   
public void buildAdminJs() {
    try {
        SimpleTrigger simpleTrigger = new SimpleTrigger();
        simpleTrigger.setName(BuildAdminJsJob.TRIGGER_NAME);
        simpleTrigger.setGroup(BuildAdminJsJob.GROUP_NAME);
        simpleTrigger.setJobName(BuildAdminJsJob.JOB_NAME);
        simpleTrigger.setJobGroup(BuildAdminJsJob.GROUP_NAME);
        simpleTrigger.setStartTime(DateUtils.addSeconds(new Date(), SettingUtil.getSetting().getBuildHtmlDelayTime()));
        simpleTrigger.setRepeatCount(0);
        simpleTrigger.setRepeatInterval(60);

        JobDetail jobDetail = scheduler.getJobDetail(BuildAdminJsJob.JOB_NAME, BuildAdminJsJob.GROUP_NAME);
        if (jobDetail != null) {
            scheduler.rescheduleJob(BuildAdminJsJob.TRIGGER_NAME, BuildAdminJsJob.GROUP_NAME, simpleTrigger);
        } else {
            jobDetail = new JobDetail(BuildAdminJsJob.JOB_NAME, BuildAdminJsJob.GROUP_NAME, BuildAdminJsJob.class);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
        }

        if (scheduler.isShutdown()) {
            scheduler.start();
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
项目:SelfSoftShop    文件:JobServiceImpl.java   
public void buildShopJs() {
    try {
        SimpleTrigger simpleTrigger = new SimpleTrigger();
        simpleTrigger.setName(BuildShopJsJob.TRIGGER_NAME);
        simpleTrigger.setGroup(BuildShopJsJob.GROUP_NAME);
        simpleTrigger.setJobName(BuildShopJsJob.JOB_NAME);
        simpleTrigger.setJobGroup(BuildShopJsJob.GROUP_NAME);
        simpleTrigger.setStartTime(DateUtils.addSeconds(new Date(), SettingUtil.getSetting().getBuildHtmlDelayTime()));
        simpleTrigger.setRepeatCount(0);
        simpleTrigger.setRepeatInterval(60);

        JobDetail jobDetail = scheduler.getJobDetail(BuildShopJsJob.JOB_NAME, BuildShopJsJob.GROUP_NAME);
        if (jobDetail != null) {
            scheduler.rescheduleJob(BuildShopJsJob.TRIGGER_NAME, BuildShopJsJob.GROUP_NAME, simpleTrigger);
        } else {
            jobDetail = new JobDetail(BuildShopJsJob.JOB_NAME, BuildShopJsJob.GROUP_NAME, BuildShopJsJob.class);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
        }

        if (scheduler.isShutdown()) {
            scheduler.start();
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
项目:SelfSoftShop    文件:JobServiceImpl.java   
public void buildErrorHtml() {
    try {
        SimpleTrigger simpleTrigger = new SimpleTrigger();
        simpleTrigger.setName(BuildErrorHtmlJob.TRIGGER_NAME);
        simpleTrigger.setGroup(BuildErrorHtmlJob.GROUP_NAME);
        simpleTrigger.setJobName(BuildErrorHtmlJob.JOB_NAME);
        simpleTrigger.setJobGroup(BuildErrorHtmlJob.GROUP_NAME);
        simpleTrigger.setStartTime(DateUtils.addSeconds(new Date(), SettingUtil.getSetting().getBuildHtmlDelayTime()));
        simpleTrigger.setRepeatCount(0);
        simpleTrigger.setRepeatInterval(60);

        JobDetail jobDetail = scheduler.getJobDetail(BuildErrorHtmlJob.JOB_NAME, BuildErrorHtmlJob.GROUP_NAME);
        if (jobDetail != null) {
            scheduler.rescheduleJob(BuildErrorHtmlJob.TRIGGER_NAME, BuildErrorHtmlJob.GROUP_NAME, simpleTrigger);
        } else {
            jobDetail = new JobDetail(BuildErrorHtmlJob.JOB_NAME, BuildErrorHtmlJob.GROUP_NAME, BuildErrorHtmlJob.class);
            scheduler.scheduleJob(jobDetail, simpleTrigger);
        }

        if (scheduler.isShutdown()) {
            scheduler.start();
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
项目:kpme    文件:BatchJobServiceImpl.java   
@SuppressWarnings("unchecked")
private void scheduleJob(Class<?> jobClass, DateTime jobDate, Map<String, String> jobGroupDataMap, Map<String, String> jobDataMap) throws SchedulerException {
    if(jobDate == null) {
        return;
    }

    String jobGroupName = BatchJobUtil.getJobGroupName(jobClass, jobGroupDataMap);
    String jobName = BatchJobUtil.getJobName(jobClass, jobDataMap);
    String[] jobNames = getScheduler().getJobNames(jobGroupName);
    if (!ArrayUtils.contains(jobNames, jobName)) {
        jobDataMap.put("date", jobDate.toString());
        Map<String, String> mergedDataMap = MapUtils.merge(jobGroupDataMap, jobDataMap);
        JobDetail jobDetail = new JobDetail(jobName, jobGroupName, jobClass, false, true, false);
        jobDetail.setJobDataMap(new JobDataMap(mergedDataMap));

        String triggerGroupName = BatchJobUtil.getTriggerGroupName(jobClass, MapUtils.merge(jobGroupDataMap, jobDataMap));
        String triggerName = BatchJobUtil.getTriggerName(jobClass, jobDate);
        Trigger trigger = new SimpleTrigger(triggerName, triggerGroupName, jobDate.toDate());
        trigger.setJobGroup(jobGroupName);
        trigger.setJobName(jobName);

        LOG.info("Scheduling " + jobDetail.getFullName() + " to be run on " + jobDate);
        this.updateStatus(jobDetail, BatchJobService.SCHEDULED_JOB_STATUS_CODE);
        getScheduler().scheduleJob(jobDetail, trigger);
    }
}
项目:cleverbus    文件:PartlyFailedMessagesPoolRoute.java   
@Override
@SuppressWarnings("unchecked")
public final void configure() throws Exception {
    String uri = RepairProcessingMsgRoute.JOB_GROUP_NAME + "/" + JOB_NAME
            + "?trigger.repeatInterval=" + (partlyFailedRepeatTime * 1000)
            + "&trigger.repeatCount=" + SimpleTrigger.REPEAT_INDEFINITELY;


    from("quartz2://" + uri)
            .routeId("partlyFailedMessageProcess" + AbstractBasicRoute.ROUTE_SUFFIX)

            // allow only if ESB not stopping
            .choice().when().method(ROUTE_BEAN, "isNotInStoppingMode")
                .beanRef("jobStarterForMessagePooling", "start")
            .end();
}
项目:spacewalk    文件:ScheduleManager.java   
/**
 * Will create/schedule a trigger for the passed in indexName.
 * Note: Only one trigger per indexName is allowed, if subsequent calls
 * are made before the current trigger finishes completion, this request
 * will be dropped.
 * @param indexName
 * @return
 */
public boolean triggerIndexTask(String indexName) {
    if (!isSupported(indexName)) {
        log.info(indexName + " is not a supported for scheduler modifications.");
        return false;
    }
    // Define a Trigger that will fire "now" and associate it with the existing job
    Trigger trigger = new SimpleTrigger("immediateTrigger-" + indexName,
            "group1", new Date());
    trigger.setJobName(indexName);
    trigger.setJobGroup(updateIndexGroupName);
    try {
        // Schedule the trigger
        log.info("Scheduling trigger: " + trigger);
        scheduler.scheduleJob(trigger);
    }
    catch (SchedulerException e) {
        log.warn("Scheduling trigger: " + trigger + " failed.");
        log.warn("Exception was caught: ",  e);
        return false;
    }
    return true;
}
项目:jooby    文件:QuartzProvider.java   
private Object describe(final Trigger trigger) {
  if (trigger.getDescription() != null) {
    return trigger.getDescription();
  }
  if (trigger instanceof SimpleTrigger) {
    return "will fire every " + ((SimpleTrigger) trigger).getRepeatInterval() + "ms";
  }
  if (trigger instanceof CronTrigger) {
    return "will fire at " + ((CronTrigger) trigger).getCronExpression();
  }
  if (trigger instanceof CalendarIntervalTrigger) {
    CalendarIntervalTrigger calendar = (CalendarIntervalTrigger) trigger;
    return "will fire every " + calendar.getRepeatInterval() + " "
        + calendar.getRepeatIntervalUnit();
  }
  if (trigger instanceof DailyTimeIntervalTrigger) {
    DailyTimeIntervalTrigger daily = (DailyTimeIntervalTrigger) trigger;
    return "will fire every " + daily.getRepeatInterval() + " "
        + daily.getRepeatIntervalUnit();
  }
  return trigger;
}
项目:jooby    文件:JobBeanExpanderTest.java   
@Test
public void shouldBuildIntervalJob() throws Exception {
  new MockUnit(Config.class)
      .expect(unit -> {
        Config config = unit.get(Config.class);
        expect(config.getString("5s")).andThrow(new ConfigException.BadPath("5s", "5s"));
      })
      .run(unit -> {
        Entry<JobDetail, Trigger> entry = JobExpander
            .jobs(unit.get(Config.class), Arrays.asList(IntervalJob.class)).entrySet()
            .iterator().next();

        JobDetail job = entry.getKey();
        assertEquals(ReflectiveJob.class, job.getJobClass());
        assertEquals(IntervalJob.class.getPackage().getName(), job.getKey().getGroup());
        assertEquals("JobBeanExpanderTest$IntervalJob.runAt", job.getKey().getName());

        SimpleTrigger trigger = (SimpleTrigger) entry.getValue();
        assertEquals(5000L, trigger.getRepeatInterval());
        assertEquals(IntervalJob.class.getPackage().getName(), trigger.getKey().getGroup());
        assertEquals("JobBeanExpanderTest$IntervalJob.runAt", trigger.getKey().getName());
      });
}
项目:jooby    文件:JobExpanderTest.java   
@Test(expected = IllegalArgumentException.class)
public void shouldBuildIntervalJobUnknownAttribute() throws Exception {
  long date = 1429984623207L;
  new MockUnit(Config.class)
      .expect(unit -> {
        Config config = unit.get(Config.class);
        expect(config.getString("5s; x= 1")).andThrow(new ConfigException.BadPath("5s", "5s"));
      })
      .expect(unit -> {
        unit.mockStatic(System.class);

        expect(System.currentTimeMillis()).andReturn(date);
      })
      .run(unit -> {
        Entry<JobDetail, Trigger> entry = JobExpander
            .jobs(unit.get(Config.class), Arrays.asList(IntervalJobUnknownAttribute.class))
            .entrySet()
            .iterator().next();

        SimpleTrigger trigger = (SimpleTrigger) entry.getValue();
        assertEquals(5000L, trigger.getRepeatInterval());
        assertEquals(new Date(date), trigger.getStartTime());
        assertEquals(-1, trigger.getRepeatCount());
      });
}
项目:quartz-couchdb-store    文件:CouchDbTriggerStoreIT.java   
@Test
public void shouldUpdateTriggerForMisfireNowWithExistingRepeatCount() throws Exception {
    String triggerName = id("fuuid");
    DateTime now = new DateTime();
    DateTime startTime = now.minusMinutes(1);
    SimpleTriggerImpl trigger = (SimpleTriggerImpl) newTrigger()
            .withIdentity(triggerName, "borgroup")
            .forJob(JobKey.jobKey("fooid", "bargroup"))
            .startAt(startTime.toDate())
            .withSchedule(simpleSchedule()
                    .withIntervalInMinutes(1)
                    .withRepeatCount(2)
                    .withMisfireHandlingInstructionNowWithExistingCount())
            .build();
    trigger.computeFirstFireTime(null);
    couchdbStore.storeTrigger(trigger, false);

    List<OperableTrigger> acquiredTriggers = couchdbStore.acquireNextTriggers(now.getMillis(), 1, 0);
    assertEquals(1, acquiredTriggers.size());

    SimpleTrigger acquiredTrigger = (SimpleTrigger) acquiredTriggers.get(0);
    assertTrue(acquiredTrigger.getNextFireTime().getTime() - now.getMillis() < 5000);
    assertEquals(2, acquiredTrigger.getRepeatCount());
}