Example usage for org.springframework.scheduling.support PeriodicTrigger setInitialDelay

List of usage examples for org.springframework.scheduling.support PeriodicTrigger setInitialDelay

Introduction

In this page you can find the example usage for org.springframework.scheduling.support PeriodicTrigger setInitialDelay.

Prototype

public void setInitialDelay(long initialDelay) 

Source Link

Document

Specify the delay for the initial execution.

Usage

From source file:com.apress.prospringintegration.endpoints.pollingconsumer.Main.java

public static void main(String[] args) {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "polling-consumer.xml");
    applicationContext.start();/*  ww  w. j av a  2 s.c om*/

    ProblemReporter problemReporter = applicationContext.getBean(ProblemReporter.class);
    TicketMessageHandler ticketMessageHandler = applicationContext.getBean(TicketMessageHandler.class);
    TicketGenerator ticketGenerator = applicationContext.getBean(TicketGenerator.class);

    QueueChannel channel = applicationContext.getBean("ticketChannel", QueueChannel.class);

    // Define the polling consumer
    PollingConsumer ticketConsumer = new PollingConsumer(channel, ticketMessageHandler);
    ticketConsumer.setReceiveTimeout(RECEIVE_TIMEOUT);
    ticketConsumer.setBeanFactory(applicationContext);

    // Setup the poller using periodic trigger
    PeriodicTrigger periodicTrigger = new PeriodicTrigger(1000);
    periodicTrigger.setInitialDelay(5000);
    periodicTrigger.setFixedRate(false);

    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(periodicTrigger);
    pollerMetadata.setMaxMessagesPerPoll(3);

    ticketConsumer.setPollerMetadata(pollerMetadata);

    // Starts the polling consumer in the other thread
    ticketConsumer.start();

    // Generates messages and sends to the channel
    List<Ticket> tickets = ticketGenerator.createTickets();
    while (true) {
        for (Ticket ticket : tickets) {
            problemReporter.openTicket(ticket);
        }
    }
}

From source file:nhs.spring.integration.App.java

public static void main(String... args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "spring-integration-context.xml");
    GameMessageHandler gameHandler = new GameMessageHandler();
    GameGenerator gameGenerator = context.getBean(GameGenerator.class);

    context.start();/*from  ww w . j a  v a2  s .c  o  m*/

    //MessageChannel input = context.getBean("input-channel", MessageChannel.class);
    //PollableChannel output = context.getBean("output-channel", PollableChannel.class);
    QueueChannel qChannel = context.getBean("game-channel", QueueChannel.class);

    PollingConsumer gameConsumer = new PollingConsumer(qChannel, gameHandler);
    gameConsumer.setReceiveTimeout(RECEIVE_TIMEOUT);
    gameConsumer.setBeanFactory(context);

    // Set up the poller using periodic trigger
    PeriodicTrigger periodicTrigger = new PeriodicTrigger(1000);
    periodicTrigger.setInitialDelay(5000);
    periodicTrigger.setFixedRate(false);

    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(periodicTrigger);
    pollerMetadata.setMaxMessagesPerPoll(3);

    gameConsumer.setPollerMetadata(pollerMetadata);

    // Starts the polling consumer in the other thread
    gameConsumer.start();

    Date today = new Date();

    // Generates messages and sends to the channel
    Game game = gameGenerator.generateGame("League of legend", "Riot Games", today, "Tom", "Michael", "AOS");

    qChannel.send(MessageBuilder.withPayload(game).build());

    /*
    PublishSubscribeChannel pubsubChannel = null;
            
    pubsubChannel.subscribe(gameHandler);
            
    input.send(MessageBuilder.withPayload("Spring Integration / Hello NHS").build());
    Message<?> reply = output.receive();
            
    System.out.println("Received :" + reply);
    */
}

From source file:org.apache.shiro.session.mgt.scheduler.SpringSessionValidationScheduler.java

/**
 * Starts session validation by creating a spring PeriodicTrigger.
 */// ww w  .  j  av  a  2 s.  co m
public void enableSessionValidation() {

    enabled = true;

    if (log.isDebugEnabled()) {
        log.debug("Scheduling session validation job using Spring Scheduler with "
                + "session validation interval of [" + sessionValidationInterval + "]ms...");
    }

    try {

        PeriodicTrigger trigger = new PeriodicTrigger(sessionValidationInterval, TimeUnit.MILLISECONDS);
        trigger.setInitialDelay(sessionValidationInterval);

        scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                if (enabled) {
                    sessionManager.validateSessions();
                }
            }
        }, trigger);

        this.enabled = true;

        if (log.isDebugEnabled()) {
            log.debug("Session validation job successfully scheduled with Spring Scheduler.");
        }

    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(
                    "Error starting the Spring Scheduler session validation job.  Session validation may not occur.",
                    e);
        }
    }
}

From source file:eu.openanalytics.rsb.component.DirectoryDepositHandler.java

@PostConstruct
public void setupChannelAdapters() {
    final List<DepositDirectoryConfiguration> depositDirectoryConfigurations = getConfiguration()
            .getDepositRootDirectories();

    if ((depositDirectoryConfigurations == null) || (depositDirectoryConfigurations.isEmpty())) {
        return;//  w  w w .j  a  v a  2s . co m
    }

    final NioFileLocker nioFileLocker = new NioFileLocker();

    for (final DepositDirectoryConfiguration depositDirectoryConfiguration : depositDirectoryConfigurations) {
        final PeriodicTrigger fileTrigger = new PeriodicTrigger(
                depositDirectoryConfiguration.getPollingPeriod(), TimeUnit.MILLISECONDS);
        fileTrigger.setInitialDelay(5000L);

        final File depositRootDirectory = depositDirectoryConfiguration.getRootDirectory();

        final FileReadingMessageSource fileMessageSource = new FileReadingMessageSource();
        fileMessageSource.setAutoCreateDirectory(true);
        fileMessageSource.setBeanFactory(beanFactory);
        fileMessageSource.setBeanName("rsb-deposit-dir-ms-" + depositRootDirectory.getPath());
        fileMessageSource.setDirectory(new File(depositRootDirectory, Configuration.DEPOSIT_JOBS_SUBDIR));
        fileMessageSource.setFilter(zipJobFilter);
        fileMessageSource.setLocker(nioFileLocker);
        fileMessageSource.afterPropertiesSet();

        final HeaderSettingMessageSourceWrapper<File> messageSource = new HeaderSettingMessageSourceWrapper<File>(
                fileMessageSource, DIRECTORY_CONFIG_HEADER_NAME, depositDirectoryConfiguration);

        final SourcePollingChannelAdapter channelAdapter = new SourcePollingChannelAdapter();
        channelAdapter.setBeanFactory(beanFactory);
        channelAdapter.setBeanName("rsb-deposit-dir-ca-" + depositRootDirectory.getPath());
        channelAdapter.setOutputChannel(directoryDepositChannel);
        channelAdapter.setSource(messageSource);
        channelAdapter.setTrigger(fileTrigger);
        channelAdapter.afterPropertiesSet();
        channelAdapter.start();

        getLogger().info("Started channel adapter: " + channelAdapter);

        channelAdapters.add(channelAdapter);
    }
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

@PostConstruct
public void setupChannelAdapters() throws URISyntaxException {
    final List<DepositEmailConfiguration> depositEmailConfigurations = getConfiguration()
            .getDepositEmailAccounts();/*from  www  . j  a  v a 2s.c  o  m*/

    if ((depositEmailConfigurations == null) || (depositEmailConfigurations.isEmpty())) {
        return;
    }

    for (final DepositEmailConfiguration depositEmailConfiguration : depositEmailConfigurations) {
        final PeriodicTrigger trigger = new PeriodicTrigger(depositEmailConfiguration.getPollingPeriod(),
                TimeUnit.MILLISECONDS);
        trigger.setInitialDelay(5000L);

        AbstractMailReceiver mailReceiver = null;

        final URI emailAccountURI = depositEmailConfiguration.getAccountURI();
        if (StringUtils.equals(emailAccountURI.getScheme(), "pop3")) {
            mailReceiver = new Pop3MailReceiver(emailAccountURI.toString());
        } else if (StringUtils.equals(emailAccountURI.getScheme(), "imap")) {
            mailReceiver = new ImapMailReceiver(emailAccountURI.toString());
            ((ImapMailReceiver) mailReceiver).setShouldMarkMessagesAsRead(true);
        } else {
            throw new IllegalArgumentException("Invalid email account URI: " + emailAccountURI);
        }

        mailReceiver.setBeanFactory(beanFactory);
        mailReceiver.setBeanName("rsb-email-ms-" + emailAccountURI.getHost() + emailAccountURI.hashCode());
        mailReceiver.setShouldDeleteMessages(true);
        mailReceiver.setMaxFetchSize(1);
        mailReceiver.afterPropertiesSet();
        final MailReceivingMessageSource fileMessageSource = new MailReceivingMessageSource(mailReceiver);
        final HeaderSettingMessageSourceWrapper<javax.mail.Message> messageSource = new HeaderSettingMessageSourceWrapper<javax.mail.Message>(
                fileMessageSource, EMAIL_CONFIG_HEADER_NAME, depositEmailConfiguration);

        final SourcePollingChannelAdapter channelAdapter = new SourcePollingChannelAdapter();
        channelAdapter.setBeanFactory(beanFactory);
        channelAdapter.setBeanName("rsb-email-ca-" + emailAccountURI.getHost() + emailAccountURI.hashCode());
        channelAdapter.setOutputChannel(emailDepositChannel);
        channelAdapter.setSource(messageSource);
        channelAdapter.setTrigger(trigger);
        channelAdapter.afterPropertiesSet();
        channelAdapter.start();

        getLogger().info("Started channel adapter: " + channelAdapter);

        channelAdapters.add(channelAdapter);
    }
}

From source file:org.jasig.ssp.service.impl.ScheduledTaskWrapperServiceImpl.java

protected Trigger tryExpressionAsPeriodicTrigger(String configValue) throws BadTriggerConfigException {
    BadTriggerConfigException longParseException = null;
    try {//w ww.j  a v  a 2  s .c  o  m
        final long period = Long.parseLong(configValue);
        if (period < 0) {
            return new DisabledTrigger();
        }
        // millis since that's what @Scheduled methods were historically
        // configured in
        return new PeriodicTrigger(period, TimeUnit.MILLISECONDS);
    } catch (NumberFormatException e) {
        longParseException = new BadTriggerConfigException(
                "Config [" + configValue + "] did not parse to a long.", configValue, e);
    } catch (IllegalArgumentException e) {
        longParseException = new BadTriggerConfigException(
                "Config [" + configValue + "] could not be used to initialize a PeriodicTrigger", configValue,
                e);
    }

    final Matcher matcher = PERIODIC_TRIGGER_WITH_INITIAL_DELAY_PATTERN.matcher(configValue);
    if (!(matcher.matches())) {
        throw new BadTriggerConfigException("Trigger expression could not be parsed as either a"
                + " simple period or as a period with an initial " + "offset. Original parse failure: ["
                + longParseException.getMessage() + "]. To be considered a period with an offset, "
                + "the expression must match this regexp" + "(without brackets): ["
                + PERIODIC_TRIGGER_WITH_INITIAL_DELAY_PATTERN + "]", configValue);
    }

    try {
        final String periodStr = matcher.group(1);
        final long periodLong = Long.parseLong(periodStr);

        if (periodLong < 0) {
            return new DisabledTrigger();
        }

        final String offsetStr = matcher.group(2);
        final long offsetLong = Long.parseLong(offsetStr);

        final PeriodicTrigger trigger = new PeriodicTrigger(periodLong, TimeUnit.MILLISECONDS);
        trigger.setInitialDelay(offsetLong);
        return trigger;
    } catch (NumberFormatException e) {
        throw new BadTriggerConfigException("Trigger expression could not be parsed as either a"
                + " simple period or as a period with an initial " + "offset. Original parse failure: ["
                + longParseException.getMessage() + "]. To be considered a period with an initial "
                + "delay, the expression must match this regexp" + "(without brackets): ["
                + PERIODIC_TRIGGER_WITH_INITIAL_DELAY_PATTERN + "]", configValue, e);
    } catch (IllegalArgumentException e) {
        throw new BadTriggerConfigException(
                "Trigger expression parsed as a period [{}] with an "
                        + "initial delay [{}] but could not be used to " + "initialize a PeriodicTrigger",
                configValue, e);
    }

}

From source file:org.springframework.cloud.stream.app.trigger.TriggerConfiguration.java

@Bean(name = TriggerConstants.TRIGGER_BEAN_NAME)
@Conditional(PeriodicTriggerCondition.class)
public Trigger periodicTrigger() {
    PeriodicTrigger trigger = new PeriodicTrigger(triggerProperties.getFixedDelay(),
            triggerProperties.getTimeUnit());
    trigger.setInitialDelay(triggerProperties.getInitialDelay());
    return trigger;
}