Java Code Examples for org.springframework.scheduling.support.CronTrigger

The following examples show how to use org.springframework.scheduling.support.CronTrigger. These examples are extracted from open source projects. 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 Project: WeBASE-Transaction   Source File: SchedulerConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    if (constants.isIfDeleteData()) {
        taskRegistrar.addTriggerTask(() -> scheduleService.deleteDataSchedule(),
            (context) -> new CronTrigger(constants.getCronDeleteData())
                .nextExecutionTime(context));
    }
    if (!constants.isIfDistributedTask()) {
        taskRegistrar.addTriggerTask(() -> scheduleService.deploySchedule(),
            (context) -> new CronTrigger(constants.getCronTrans())
                .nextExecutionTime(context));
        taskRegistrar.addTriggerTask(() -> scheduleService.transSchedule(),
            (context) -> new CronTrigger(constants.getCronTrans())
                .nextExecutionTime(context));
    }
}
 
Example 2
Source Project: super-cloudops   Source File: EngineTaskScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Startup pipeline job.
 * 
 * @param trigger
 * @param project
 * @param task
 * @param taskInstances
 */
private void startupTimingPipeline(CustomEngine customEngine) {
	log.info("Startup timing pipeline for customEngineId: {}, expression: '{}'", customEngine.getId(), customEngine.getCron());
	stopTimingPipeline(customEngine);
	if (Objects.isNull(customEngine.getStatus()) ||  customEngine.getStatus() == 0) {
		return;
	}
	CronTrigger cronTrigger = checkCron(customEngine.getCron());
	if(Objects.isNull(cronTrigger)){
		log.error("cron is error, cron={}",customEngine.getCron());
		return;
	}
	TimingEngineProvider provider = beanFactory.getBean(TimingEngineProvider.class, new Object[] {customEngine});
	ScheduledFuture<?> future = taskScheduler.schedule(provider, new CronTrigger(customEngine.getCron()));
	EngineTaskScheduler.map.put(getTimingPipelineKey(customEngine.getId()), future);
}
 
Example 3
Source Project: super-cloudops   Source File: PipelineTaskScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Startup pipeline job.
 * 
 * @param trigger
 * @param project
 * @param task
 * @param taskInstances
 */
private void startupTimingPipeline(Trigger trigger, Project project, Task task, List<TaskInstance> taskInstances) {
	if (log.isInfoEnabled()) {
		log.info("Startup timing pipeline for triggerId: {}, expression: '{}', instances: {} ", trigger.getId(),
				trigger.getCron(), taskInstances);
	}
	stopTimingPipeline(trigger);

	if (trigger.getEnable() != 1) {
		return;
	}

	TimingPipelineProvider provider = beanFactory.getBean(TimingPipelineProvider.class,
			new Object[] { trigger, project, task, taskInstances });
	ScheduledFuture<?> future = taskScheduler.schedule(provider, new CronTrigger(trigger.getCron()));
	// TODO distributed cluster??
	PipelineTaskScheduler.map.put(getTimingPipelineKey(trigger), future);
}
 
Example 4
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNextFormattedRuntime() {
    final Long millisecondsToNextRun = 10000L;
    ZonedDateTime currentUTCTime = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime expectedDateTime = currentUTCTime.plus(millisecondsToNextRun, ChronoUnit.MILLIS);
    int seconds = expectedDateTime.getSecond();
    if (seconds >= 30) {
        expectedDateTime = expectedDateTime.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
    } else {
        expectedDateTime = expectedDateTime.truncatedTo(ChronoUnit.MINUTES);
    }
    String expectedNextRunTime = expectedDateTime.format(DateTimeFormatter.ofPattern(ScheduledTask.FORMAT_PATTERN)) + " UTC";

    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.getDelay(TimeUnit.MILLISECONDS)).thenReturn(millisecondsToNextRun);
    task.scheduleExecution(validCronExpression);
    Optional<String> nextRunTime = task.getFormatedNextRunTime();
    assertTrue(nextRunTime.isPresent());
    String nextTime = nextRunTime.get();
    assertEquals(expectedNextRunTime, nextTime);
}
 
Example 5
Source Project: blackduck-alert   Source File: ScheduledTask.java    License: Apache License 2.0 6 votes vote down vote up
public void scheduleExecution(String cron) {
    if (StringUtils.isNotBlank(cron)) {
        try {
            CronTrigger cronTrigger = new CronTrigger(cron, TimeZone.getTimeZone("UTC"));
            unscheduleTask();
            logger.info("Scheduling {} with cron : {}", getTaskName(), cron);
            future = taskScheduler.schedule(this, cronTrigger);
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
        }
    } else {
        if (future != null) {
            logger.info("Un-Scheduling {}", getTaskName());
            unscheduleTask();
        }
    }
}
 
Example 6
/**
 * Only set next execution time if the job is not continuous.
 */
public void setNextExecutionTime( Date nextExecutionTime )
{
    if ( cronExpression == null || cronExpression.equals( "" ) || cronExpression.equals( "* * * * * ?" ) )
    {
        return;
    }

    if ( nextExecutionTime != null )
    {
        this.nextExecutionTime = nextExecutionTime;
    }
    else
    {
        this.nextExecutionTime = new CronTrigger( cronExpression ).nextExecutionTime( new SimpleTriggerContext() );
    }
}
 
Example 7
@Override
protected void doStart() throws Exception {
    if (! localRegistryEnabled) {
        if (enabled) {
            super.doStart();
            logger.info("Sync service has been initialized with cron [{}]", cronTrigger);
            // Sync must start only when doStart() is invoked, that's the reason why we are not
            // using @Scheduled annotation on doSync() method.
            scheduler.schedule(this, new CronTrigger(cronTrigger));
        } else {
            logger.warn("Sync service has been disabled");
        }
    } else {
        logger.warn("Sync service is disabled because local registry mode is enabled");
    }
}
 
Example 8
Source Project: gravitee-gateway   Source File: ScheduledSyncService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() throws Exception {
    if (! localRegistryEnabled) {
        if (enabled) {
            super.doStart();
            logger.info("Sync service has been initialized with cron [{}]", cronTrigger);

            logger.info("Associate a new HTTP handler on {}", PATH);

            // Create and associate handler
            SyncHandler syncHandler = new SyncHandler();
            applicationContext.getAutowireCapableBeanFactory().autowireBean(syncHandler);
            router.get(PATH).produces(MediaType.APPLICATION_JSON).handler(syncHandler);

            // Star cron
            scheduler.schedule(this, new CronTrigger(cronTrigger));
        } else {
            logger.warn("Sync service has been disabled");
        }
    } else {
        logger.warn("Sync service is disabled because local registry mode is enabled");
    }
}
 
Example 9
Source Project: spring-batch-lightmin   Source File: CronScheduler.java    License: Apache License 2.0 6 votes vote down vote up
public CronScheduler(final SchedulerConstructorWrapper schedulerConstructorWrapper) {
    this.jobConfiguration = schedulerConstructorWrapper.getJobConfiguration();
    this.threadPoolTaskScheduler = schedulerConstructorWrapper.getThreadPoolTaskScheduler();
    this.jobSchedulerConfiguration = this.jobConfiguration.getJobSchedulerConfiguration();
    this.timeZone = TimeZone.getDefault();
    this.trigger = new CronTrigger(this.jobSchedulerConfiguration.getCronExpression(), this.timeZone);
    this.job = schedulerConstructorWrapper.getJob();

    this.jobRunner = new JobRunner(this.job,
            schedulerConstructorWrapper.getJobLauncher(),
            schedulerConstructorWrapper.getJobParameters(),
            schedulerConstructorWrapper.getJobIncrementer());
    final SchedulerStatus schedulerStatus;
    if (this.jobSchedulerConfiguration.getSchedulerStatus() != null) {
        schedulerStatus = this.jobSchedulerConfiguration.getSchedulerStatus();
    } else {
        schedulerStatus = SchedulerStatus.INITIALIZED;
    }
    this.setStatus(schedulerStatus);
}
 
Example 10
Source Project: es   Source File: DynamicTaskApiImpl.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized void startTask(boolean forceStart, Long... taskDefinitionIds) {
    for(Long taskDefinitionId : taskDefinitionIds) {
        TaskDefinition td = taskDefinitionService.findOne(taskDefinitionId);
        if(td == null || (forceStart == false && Boolean.TRUE.equals(td.getStart()))) {
            return;
        }

        try {
            ScheduledFuture<?> future = taskScheduler.schedule(createTask(td), new CronTrigger(td.getCron()));
            taskMap.put(taskDefinitionId, future);
            td.setStart(Boolean.TRUE);
        } catch (Exception e) {
            logger.error("start task error, task id:" + taskDefinitionId, e);
            td.setDescription(e.getMessage());
        }
        taskDefinitionService.update(td);
    }
}
 
Example 11
Source Project: WeBASE-Front   Source File: ScheduledTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void changeCron() {
//        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        stopCron();// 先停止,在开启.
        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("*/10 * * * * *"));
        System.out.println("DynamicTaskController.changeCron()");
    }
 
Example 12
Source Project: chronus   Source File: AbstractJob.java    License: Apache License 2.0 5 votes vote down vote up
protected void configureTasks(ScheduledTaskRegistrar taskRegistrar, Runnable task, String cron) {
    taskRegistrar.addTriggerTask(task, (TriggerContext triggerContext) -> {
        CronTrigger trigger = new CronTrigger(cron);
        Date nextExec = trigger.nextExecutionTime(triggerContext);
        return nextExec;
    });
}
 
Example 13
public DatabaseMySQLTraceLogFlushHandler(DataSource dataSource) {
    Assert.notNull(dataSource, "DatabaseTraceLogFlushHandler must have dataSource.");
    this.dataSource = dataSource;
    doWithConnection(createTableIfNotExist);
    tableReady = true;
    threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setDaemon(true);
    threadPoolTaskScheduler.setThreadNamePrefix("TraceLogFlush");
    threadPoolTaskScheduler.initialize();
    threadPoolTaskScheduler.schedule(cleanerTask,
        new CronTrigger(System.getProperty("rabbit.trace.flush.trigger", "0 0 1 * * ?")));
}
 
Example 14
Source Project: server   Source File: TestPlanService.java    License: MIT License 5 votes vote down vote up
/**
 * 添加或更新定时任务
 */
private synchronized void addOrUpdateScheduleTask(TestPlan testPlan) {
    ScheduledFuture future = TEST_PLAN_SCHEDULED_FUTURE_MAP.get(testPlan.getId());
    if (future != null) {
        // 取消上一次设置的定时任务
        log.info("cancel schedule, testPlan: {}", testPlan.getName());
        future.cancel(true);
    }
    log.info("add schedule, testPlan: {}", testPlan.getName());
    future = TASK_SCHEDULER.schedule(() -> testTaskService.commit(testPlan.getId(), testPlan.getCreatorUid()), new CronTrigger(testPlan.getCronExpression()));
    TEST_PLAN_SCHEDULED_FUTURE_MAP.put(testPlan.getId(), future);
}
 
Example 15
Source Project: hygieia-core   Source File: CollectorTaskTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void onStartup() {
    Collector c = new Collector();
    c.setOnline(false);
    when(baseCollectorRepository.findByName(COLLECTOR_NAME)).thenReturn(c);
    task.onStartup();

    assertThat(c.isOnline(), is(true));
    verify(baseCollectorRepository, times(1)).save(c);
    verify(taskScheduler).schedule(any(TestCollectorTask.class), any(CronTrigger.class));
}
 
Example 16
Source Project: gem   Source File: GemTaskServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
	taskRegistrar.addTriggerTask(() -> {
		// 定时任务的业务逻辑
		System.out.println("动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
	}, (triggerContext) -> {
		// 定时任务触发,可修改定时任务的执行周期
		CronTrigger trigger = new CronTrigger(cron);
		Date nextExecDate = trigger.nextExecutionTime(triggerContext);
		return nextExecDate;
	});
}
 
Example 17
Source Project: super-cloudops   Source File: EngineTaskScheduler.java    License: Apache License 2.0 5 votes vote down vote up
private CronTrigger checkCron(String cron){
	try {
		return new CronTrigger(cron);
	}catch (Exception e){
		e.printStackTrace();
	}
	return null;
}
 
Example 18
Source Project: lion   Source File: ScheduleConfig.java    License: Apache License 2.0 5 votes vote down vote up
private Trigger getTrigger(Schedule schedule) {
    return triggerContext -> {
        // 将Cron 0/1 * * * * ? 输入取得下一次执行的时间
        final CronTrigger cronTrigger = new CronTrigger(schedule.getCron());
        final Date date = cronTrigger.nextExecutionTime(triggerContext);
        return date;
    };
}
 
Example 19
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextFormattedRuntimeNullFuture() {
    Mockito.doReturn(null).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    task.scheduleExecution(validCronExpression);
    Optional<String> nextRunTime = task.getFormatedNextRunTime();
    assertFalse(nextRunTime.isPresent());
}
 
Example 20
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextFormattedRuntimeFutureCancelled() {
    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.isCancelled()).thenReturn(true);
    task.scheduleExecution(validCronExpression);
    Optional<String> nextRunTime = task.getFormatedNextRunTime();
    assertFalse(nextRunTime.isPresent());
}
 
Example 21
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextFormattedRuntimeFutureDone() {
    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.isDone()).thenReturn(true);
    task.scheduleExecution(validCronExpression);
    Optional<String> nextRunTime = task.getFormatedNextRunTime();
    assertFalse(nextRunTime.isPresent());
}
 
Example 22
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextRuntime() {
    final Long expectedNextRun = 10000L;
    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.getDelay(TimeUnit.MILLISECONDS)).thenReturn(expectedNextRun);
    task.scheduleExecution(validCronExpression);
    Optional<Long> actualNextRun = task.getMillisecondsToNextRun();
    assertTrue(actualNextRun.isPresent());
    assertEquals(expectedNextRun, actualNextRun.get());
}
 
Example 23
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextRuntimeNullFuture() {
    Mockito.doReturn(null).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    task.scheduleExecution(validCronExpression);
    Optional<Long> actualNextRun = task.getMillisecondsToNextRun();
    assertFalse(actualNextRun.isPresent());
}
 
Example 24
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextRuntimeFutureCancelled() {
    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.isCancelled()).thenReturn(true);
    task.scheduleExecution(validCronExpression);
    Optional<Long> actualNextRun = task.getMillisecondsToNextRun();
    assertFalse(actualNextRun.isPresent());
}
 
Example 25
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNextRuntimeFutureDone() {
    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.isDone()).thenReturn(true);
    task.scheduleExecution(validCronExpression);
    Optional<Long> actualNextRun = task.getMillisecondsToNextRun();
    assertFalse(actualNextRun.isPresent());
}
 
Example 26
Source Project: blackduck-alert   Source File: ScheduledTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testScheduleCronExecutionUnschedule() {
    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    task.scheduleExecution(validCronExpression);
    Mockito.verify(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    task.scheduleExecution(ScheduledTask.STOP_SCHEDULE_EXPRESSION);
    Mockito.verify(taskScheduler, Mockito.times(1)).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
}
 
Example 27
Source Project: Taroco-Scheduler   Source File: TaskManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 启动动态定时任务
 * 支持:
 * 1 cron时间表达式,立即执行
 * 2 startTime + period,指定时间,定时进行
 * 3 period,定时进行,立即开始
 * 4 startTime,指定时间执行
 *
 * @param targetBean     目标bean名称
 * @param targetMethod   方法
 * @param cronExpression cron表达式
 * @param startTime      指定执行时间
 * @param period         定时进行,立即开始
 * @param params         给方法传递的参数
 * @param extKeySuffix   任务后缀名
 */
private void scheduleTask(String targetBean, String targetMethod, String cronExpression,
                          Date startTime, Long period, String params, String extKeySuffix) {
    String scheduleKey = ScheduleUtil.buildScheduleKey(targetBean, targetMethod, extKeySuffix);
    try {
        if (!SCHEDULE_FUTURES.containsKey(scheduleKey)) {
            ScheduledFuture<?> scheduledFuture = null;
            ScheduledMethodRunnable scheduledMethodRunnable = buildScheduledRunnable(targetBean, targetMethod, params, extKeySuffix);
            if (scheduledMethodRunnable != null) {
                if (StringUtils.isNotEmpty(cronExpression)) {
                    Trigger trigger = new CronTrigger(cronExpression);
                    scheduledFuture = zkClient.getTaskGenerator().schedule(scheduledMethodRunnable,
                            trigger);
                } else if (startTime != null) {
                    if (period > 0) {
                        scheduledFuture = zkClient.getTaskGenerator().scheduleAtFixedRate(scheduledMethodRunnable, startTime, period);
                    } else {
                        scheduledFuture = zkClient.getTaskGenerator().schedule(scheduledMethodRunnable, startTime);
                    }
                } else if (period > 0) {
                    scheduledFuture = zkClient.getTaskGenerator().scheduleAtFixedRate(scheduledMethodRunnable, period);
                }
                if (null != scheduledFuture) {
                    SCHEDULE_FUTURES.put(scheduleKey, scheduledFuture);
                    log.info("成功启动动态任务, bean=" + targetBean + ", method=" + targetMethod + ", params=" + params + ", extKeySuffix=" + extKeySuffix);
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
 
Example 28
@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();
        logger.info("Sync service has been initialized with cron [{}]", cronTrigger);
        // Sync must start only when doStart() is invoked, that's the reason why we are not
        // using @Scheduled annotation on doSync() method.
        scheduler.schedule(this, new CronTrigger(cronTrigger));
    } else {
        logger.warn("Sync service has been disabled");
    }
}
 
Example 29
@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();
        logger.info("Sync service has been initialized with cron [{}]", cronTrigger);
        // Sync must start only when doStart() is invoked, that's the reason why we are not
        // using @Scheduled annotation on doSync() method.
        scheduler.schedule(this, new CronTrigger(cronTrigger));
    } else {
        logger.warn("Sync service has been disabled");
    }
}
 
Example 30
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
	TaskDefine taskDefine = getTaskDefine(task);
	if(trigger instanceof CronTrigger){
		CronTrigger cronTrigger = (CronTrigger)trigger;
		taskDefine.setCronExpression(cronTrigger.getExpression());
		LOGGER.info("spring task init------trigger:" + cronTrigger.getExpression());
	}
	addTask(task, taskDefine);
	return super.schedule(taskWrapper(task), trigger);
}