org.springframework.scheduling.Trigger Java Examples

The following examples show how to use org.springframework.scheduling.Trigger. 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: SecretLeaseContainerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRotateGenericSecretNow() {

	when(this.taskScheduler.schedule(any(Runnable.class), any(Trigger.class))).thenReturn(this.scheduledFuture);

	when(this.vaultOperations.read(this.rotatingGenericSecret.getPath())).thenReturn(
			createGenericSecrets(Collections.singletonMap("key", "value")),
			createGenericSecrets(Collections.singletonMap("foo", "bar")));

	this.secretLeaseContainer.addRequestedSecret(this.rotatingGenericSecret);
	this.secretLeaseContainer.start();

	this.secretLeaseContainer.rotate(this.rotatingGenericSecret);

	ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class));
	verify(this.scheduledFuture).cancel(false);
	verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class));

	ArgumentCaptor<SecretLeaseEvent> createdEvents = ArgumentCaptor.forClass(SecretLeaseEvent.class);
	verify(this.leaseListenerAdapter, times(3)).onLeaseEvent(createdEvents.capture());
}
 
Example #2
Source File: ConcurrentTaskScheduler.java    From java-technology-stack with MIT License 6 votes vote down vote up
public ScheduledFuture<?> schedule(Runnable task, final Trigger trigger) {
	ManagedScheduledExecutorService executor = (ManagedScheduledExecutorService) scheduledExecutor;
	return executor.schedule(task, new javax.enterprise.concurrent.Trigger() {
		@Override
		@Nullable
		public Date getNextRunTime(@Nullable LastExecution le, Date taskScheduledTime) {
			return (trigger.nextExecutionTime(le != null ?
					new SimpleTriggerContext(le.getScheduledStart(), le.getRunStart(), le.getRunEnd()) :
					new SimpleTriggerContext()));
		}
		@Override
		public boolean skipRun(LastExecution lastExecution, Date scheduledRunTime) {
			return false;
		}
	});
}
 
Example #3
Source File: ConcurrentTaskScheduler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
	try {
		if (this.enterpriseConcurrentScheduler) {
			return new EnterpriseConcurrentTriggerScheduler().schedule(decorateTask(task, true), trigger);
		}
		else {
			ErrorHandler errorHandler =
					(this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
			return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();
		}
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
	}
}
 
Example #4
Source File: ConcurrentTaskScheduler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public ScheduledFuture<?> schedule(Runnable task, final Trigger trigger) {
	ManagedScheduledExecutorService executor = (ManagedScheduledExecutorService) scheduledExecutor;
	return executor.schedule(task, new javax.enterprise.concurrent.Trigger() {
		@Override
		@Nullable
		public Date getNextRunTime(@Nullable LastExecution le, Date taskScheduledTime) {
			return (trigger.nextExecutionTime(le != null ?
					new SimpleTriggerContext(le.getScheduledStart(), le.getRunStart(), le.getRunEnd()) :
					new SimpleTriggerContext()));
		}
		@Override
		public boolean skipRun(LastExecution lastExecution, Date scheduledRunTime) {
			return false;
		}
	});
}
 
Example #5
Source File: ProxyTaskScheduler.java    From lemon with Apache License 2.0 6 votes vote down vote up
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
    if (!enabled) {
        logger.debug("skip : {}", task);

        return null;
    }

    ScheduledFuture<?> future = instance.schedule(task, trigger);
    String runnableKey = findRunnableKey(task);

    if (Boolean.FALSE.equals(skipMap.get(runnableKey))) {
        future.cancel(true);
    }

    return future;
}
 
Example #6
Source File: SecretLeaseContainerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldPublishRenewalErrors() {

	prepareRenewal();
	when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class)))
			.thenThrow(new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT));

	this.secretLeaseContainer.start();

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.leaseListenerAdapter).onLeaseEvent(any(SecretLeaseCreatedEvent.class));
	verify(this.leaseListenerAdapter).onLeaseError(this.captor.capture(), any(VaultException.class));
	verifyNoMoreInteractions(this.leaseListenerAdapter);

	SecretLeaseEvent leaseEvent = this.captor.getValue();

	assertThat(leaseEvent.getSource()).isEqualTo(this.requestedSecret);
	assertThat(leaseEvent.getLease()).isNotNull();
}
 
Example #7
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldRunTokenRenewal() {

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10))));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.restOperations).postForObject(eq("auth/token/renew-self"),
			eq(new HttpEntity<>(
					VaultHttpHeaders.from(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))))),
			any(Class.class));
	verify(this.clientAuthentication, times(1)).login();
	verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRenewedEvent.class));
	verify(this.listener).onAuthenticationEvent(any(AfterLoginTokenRenewedEvent.class));
}
 
Example #8
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReScheduleTokenRenewalAfterSuccessfulRenewal() {

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10))));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.taskScheduler, times(2)).schedule(any(Runnable.class), any(Trigger.class));
}
 
Example #9
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldNotScheduleRenewalIfRenewalTtlExceedsThreshold() {

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class));
}
 
Example #10
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReLoginIfRenewalTtlExceedsThreshold() {

	when(this.clientAuthentication.login()).thenReturn(
			LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)),
			LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenReturn(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2))));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	assertThat(this.sessionManager.getSessionToken())
			.isEqualTo(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));

	verify(this.clientAuthentication, times(2)).login();
	verify(this.listener, times(2)).onAuthenticationEvent(any(AfterLoginEvent.class));
	verify(this.listener).onAuthenticationEvent(any(LoginTokenExpiredEvent.class));
}
 
Example #11
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReLoginIfRenewalFails() {

	when(this.clientAuthentication.login()).thenReturn(
			LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)),
			LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenThrow(new ResourceAccessException("Connection refused"));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	assertThat(this.sessionManager.getSessionToken())
			.isEqualTo(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));

	verify(this.clientAuthentication, times(2)).login();
}
 
Example #12
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUseTaskScheduler() {

	this.sessionManager = new LifecycleAwareSessionManager(this.clientAuthentication, this.taskScheduler,
			this.restOperations);

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));

	ArgumentCaptor<Trigger> triggerCaptor = ArgumentCaptor.forClass(Trigger.class);

	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(any(Runnable.class), triggerCaptor.capture());

	assertThat(triggerCaptor.getValue().nextExecutionTime(null)).isNotNull();
	assertThat(triggerCaptor.getValue().nextExecutionTime(null)).isNull();
}
 
Example #13
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldNotReScheduleTokenRenewalAfterFailedRenewal() {

	when(this.clientAuthentication.login())
			.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any()))
			.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class));
}
 
Example #14
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReScheduleTokenRenewalAfterSuccessfulRenewal() {

	mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));

	when(this.responseSpec.bodyToMono(VaultResponse.class))
			.thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));

	runnableCaptor.getValue().run();

	verify(this.taskScheduler, times(2)).schedule(any(Runnable.class), any(Trigger.class));
}
 
Example #15
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReLoginIfRenewalTtlExceedsThreshold() {

	when(this.tokenSupplier.getVaultToken()).thenReturn(
			Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))),
			Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))));
	when(this.responseSpec.bodyToMono(VaultResponse.class))
			.thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2)))));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	this.sessionManager.getSessionToken().as(StepVerifier::create)
			.expectNext(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))).verifyComplete();

	verify(this.tokenSupplier, times(2)).getVaultToken();
	verify(this.listener, times(2)).onAuthenticationEvent(any(AfterLoginEvent.class));
	verify(this.listener).onAuthenticationEvent(any(LoginTokenExpiredEvent.class));
}
 
Example #16
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReLoginIfRenewFails() {

	when(this.tokenSupplier.getVaultToken()).thenReturn(
			Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))),
			Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))));
	when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.error(new RuntimeException("foo")));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	this.sessionManager.getSessionToken().as(StepVerifier::create)
			.expectNext(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))).verifyComplete();

	verify(this.tokenSupplier, times(2)).getVaultToken();
}
 
Example #17
Source File: ReactiveLifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRetainTokenAfterRenewalFailure() {

	when(this.tokenSupplier.getVaultToken()).thenReturn(
			Mono.just(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))),
			Mono.just(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5))));
	when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.error(new RuntimeException("foo")));
	this.sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError());

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	this.sessionManager.getSessionToken().as(StepVerifier::create)
			.expectNext(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5))).verifyComplete();

	verify(this.tokenSupplier).getVaultToken();
}
 
Example #18
Source File: SecretLeaseContainerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldRenewLease() {

	prepareRenewal();

	when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class)))
			.thenReturn(Lease.of("new_lease", Duration.ofSeconds(70), true));

	this.secretLeaseContainer.start();

	ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class));

	captor.getValue().run();
	verifyZeroInteractions(this.scheduledFuture);
	verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class));
}
 
Example #19
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRetainTokenAfterRenewalFailure() {

	when(this.clientAuthentication.login()).thenReturn(
			LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)),
			LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenThrow(new ResourceAccessException("Connection refused"));
	this.sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError());

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	assertThat(this.sessionManager.getSessionToken())
			.isEqualTo(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));

	verify(this.clientAuthentication).login();
}
 
Example #20
Source File: DiskCleanupTaskTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@Test
void wontScheduleOnNonUnixWithSudo() throws IOException {
    Assumptions.assumeTrue(!SystemUtils.IS_OS_UNIX);
    final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.exists()).thenReturn(true);
    final DataServices dataServices = Mockito.mock(DataServices.class);
    Mockito.when(dataServices.getPersistenceService()).thenReturn(Mockito.mock(PersistenceService.class));
    Assertions.assertThat(
        new DiskCleanupTask(
            new DiskCleanupProperties(),
            scheduler,
            jobsDir,
            dataServices,
            JobsProperties.getJobsPropertiesDefaults(),
            Mockito.mock(Executor.class),
            new SimpleMeterRegistry()
        )
    ).isNotNull();
    Mockito.verify(scheduler, Mockito.never()).schedule(Mockito.any(Runnable.class), Mockito.any(Trigger.class));
}
 
Example #21
Source File: ConcurrentTaskScheduler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
	try {
		if (this.enterpriseConcurrentScheduler) {
			return new EnterpriseConcurrentTriggerScheduler().schedule(decorateTask(task, true), trigger);
		}
		else {
			ErrorHandler errorHandler =
					(this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
			return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();
		}
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
	}
}
 
Example #22
Source File: SecretLeaseContainerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void shouldRetainLeaseAfterRenewalFailure() {

	prepareRenewal();
	when(this.vaultOperations.doWithSession(any(RestOperationsCallback.class)))
			.thenThrow(new VaultException("Renewal failure"));

	this.secretLeaseContainer.setLeaseStrategy(LeaseStrategy.retainOnError());
	this.secretLeaseContainer.start();

	ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.taskScheduler).schedule(captor.capture(), any(Trigger.class));
	captor.getValue().run();

	verify(this.taskScheduler, times(2)).schedule(captor.capture(), any(Trigger.class));
	captor.getValue().run();

	verify(this.vaultOperations, times(2)).doWithSession(any(RestOperationsCallback.class));
}
 
Example #23
Source File: ThreadPoolTaskScheduler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
	ScheduledExecutorService executor = getScheduledExecutor();
	try {
		ErrorHandler errorHandler = this.errorHandler;
		if (errorHandler == null) {
			errorHandler = TaskUtils.getDefaultErrorHandler(true);
		}
		return new ReschedulingRunnable(task, trigger, executor, errorHandler).schedule();
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}
 
Example #24
Source File: SpringTaskProcessor.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void process(String jobClassName, String jobConfig) {
    try {
        Runnable runnable = (Runnable) applicationContext.getBean(Class
                .forName(jobClassName));
        Trigger trigger = new CronTrigger(jobConfig);
        taskScheduler.schedule(runnable, trigger);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}
 
Example #25
Source File: ConcurrentTaskScheduler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
	try {
		if (this.enterpriseConcurrentScheduler) {
			return new EnterpriseConcurrentTriggerScheduler().schedule(decorateTask(task, true), trigger);
		}
		else {
			ErrorHandler errorHandler = (this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true));
			return new ReschedulingRunnable(task, trigger, this.scheduledExecutor, errorHandler).schedule();
		}
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task, ex);
	}
}
 
Example #26
Source File: ThreadPoolTaskGenerator.java    From Taroco-Scheduler with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ScheduledFuture<?> schedule(Runnable runnable, Trigger trigger) {
    ScheduledFuture scheduledFuture = null;
    try {
        Task task = resolveTaskName(runnable);
        if (task.getType().equals(DefaultConstants.TYPE_SPRING_TASK)) {
            // Spring 本地任务需要先添加到集群管理, 由集群统一分配后再执行
            if (!scheduleTask.isExistsTask(task)) {
                task.setStartTime(new Date(System.currentTimeMillis()));
                String cronEx = trigger.toString();
                int index = cronEx.indexOf(":");
                if (index >= 0) {
                    cronEx = cronEx.substring(index + 1);
                    task.setCronExpression(cronEx.trim());
                }
                scheduleTask.addTask(task);
            }
        } else {
            // 动态任务直接执行
            scheduledFuture = super.schedule(taskWrapper(runnable), trigger);
            log.info("添加 Taroco 动态任务[" + task.stringKey() + "]");
        }
    } catch (Exception e) {
        log.error("update task error", e);
    }
    return scheduledFuture;
}
 
Example #27
Source File: TracedThreadPoolTaskSchedulerTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void scheduleWithTrigger() {
  final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class);
  final Trigger trigger = mock(Trigger.class);
  scheduler.schedule(mockRunnable, trigger);
  verify(delegate).schedule(argumentCaptor.capture(), eq(trigger));
  verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer);
}
 
Example #28
Source File: DatabaseCleanupTaskTest.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure the trigger returned is accurate.
 */
@Test
void canGetTrigger() {
    final String expression = "0 0 1 * * *";
    this.environment.setProperty(DatabaseCleanupProperties.EXPRESSION_PROPERTY, expression);
    Mockito.when(this.cleanupProperties.getExpression()).thenReturn("0 0 0 * * *");
    final Trigger trigger = this.task.getTrigger();
    if (trigger instanceof CronTrigger) {
        final CronTrigger cronTrigger = (CronTrigger) trigger;
        Assertions.assertThat(cronTrigger.getExpression()).isEqualTo(expression);
    } else {
        Assertions.fail("Trigger was not of expected type: " + CronTrigger.class.getName());
    }
}
 
Example #29
Source File: TriggerConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: DatabaseCleanupTask.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Trigger getTrigger() {
    final String expression = this.environment.getProperty(
        DatabaseCleanupProperties.EXPRESSION_PROPERTY,
        String.class,
        this.cleanupProperties.getExpression()
    );
    return new CronTrigger(expression, JobConstants.UTC);
}