xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd"
(2) 开启任务注解扫描,配置线程数
<!-- task任务扫描注解 -->
<task:annotation-driven scheduler="myScheduler"/>
<!--配置定时任务的线程池数量 -->
<task:scheduler id="myScheduler" pool-size="2"/>
<!-- 扫描位置 -->
<context:component-scan base-package="com.wutongyu.job"/>
(3) 任务类,注解任务调度正则
package com.wutongyu.job;
@Component
public class EtsLockAssetJob{
private static final Logger log = LoggerFactory.getLogger(EtsLockAssetJob.class);
@Scheduled(cron = "0 */3 * * * ?")
public void execute(){
//业务逻辑
}
}
方法二:
(1) spring配置文件中加入task的命名空间
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd"
(2) 注解声明corn正则,指定任务执行方法
//定时注解驱动
<task:annotation-driven />
//进行定时任务的类,将其定义为一个bean
<bean id="etsLockAssetService" class="com.wutongyu.impl.EtsLockAssetServiceImpl"></bean>
//通过task标签,定义定时功能
<task:scheduled-tasks>
<task:scheduled ref="etsLockAssetService" method="executeTest" cron="0 */3 * * * ?" />
</task:scheduled-tasks>
(3) 任务类
@Service
public class EtsLockAssetServiceImpl implements EtsLockAssetService
{
@Override
public void executeTest()
{
//业务逻辑
}
}
2 动态周期任务
@Component
@EnableScheduling
public class SiemHazardAnalysisJob implements SchedulingConfigurer {
private Log log = LogFactory.getLog(SiemHazardAnalysisJob.class);
@Autowired
private ElasticsearchDubboService elasticsearchDubboService;
public static String cron="0 */1 * * * ?";
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
elasticsearchDubboService.hazardAnalysisJob();
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 任务触发,可修改任务的执行周期
CronTrigger trigger = new CronTrigger(cron);
log.error("修改潜在危害分析定时任务成功:" + cron);
Date nextExecutor = trigger.nextExecutionTime(triggerContext);
return nextExecutor;
}
});
}
}
说明:外部对cron正则进行修改,待下次执行任务时,在任务不间断的前提下,调整任务周期
cron正则:
0 */3 * * * ? :间隔三分钟触发一次
0 0 */1 * * ? :每小时触发一次
0 30 10 * * ? :每天上午10:30触发一次
0 0/30 9-12 * * ? :早上9点到中午12点内每30分钟触发一次
0 0/5 9 * * ? :在每天早上9点到早上9:59期间,每5分钟触发一次
0 30 10 ? * MON-FRI :周一至周五的上午10:30触发