我使用@Scheduled注释在Spring中定义具有cron样式模式的预定作业.
cron模式存储在配置属性文件中.实际上有两个属性文件:一个默认配置,一个依赖于环境的配置文件配置(例如dev,test,prod customer 1,prod customer 2等)并覆盖一些默认值.
我在spring上下文中配置了一个属性占位符bean,它允许我使用${}样式占位符从我的属性文件中导入值.
作业bean看起来像这样:
@Component
public class ImagesPurgeJob implements Job {
private Logger logger = Logger.getLogger(this.getClass());
@Override
@Transactional(readOnly=true)
@Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}")
public void execute() {
//Do something
//can use DAO or other autowired beans here
}
}
Run Code Online (Sandbox Code Playgroud)
我的上下文XML的相关部分:
<!-- Enable configuration of scheduled tasks via annotations -->
<task:annotation-driven/>
<!-- Load configuration files and allow '${}' style placeholders -->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/default-config.properties</value>
<value>classpath:config/environment-config.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" …Run Code Online (Sandbox Code Playgroud) 有没有办法启动或停止使用上下文文件或@Scheduled注释初始化的Spring Scheduled Tasks安排的任务?
我想在需要时启动任务,并在不再需要运行任务时停止它.
如果这是不可能的,那么将弹簧变量注入线程的替代方法是什么?
我想哭我的调度程序直到我的任务完成。如果有时间执行第二个调度程序,它必须等到上一个任务未完成。我在 java Boot 应用程序中使用 @Schedule 。我想每 5 分钟将数据插入到数据库中,但我想保持我的日程安排,直到插入数据不完整仍然有时间进行第二次执行。 演示代码
@Scheduled(fixedRate = 2000)
public void scheduleTaskWithFixedRate() {
logger.info("Fixed Rate Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now()) );
}
Run Code Online (Sandbox Code Playgroud)