5.21. Spring boot with Scheduling

简介:

项目中经常会用到计划任务,spring Boot 中通过@EnableScheduling启用计划任务,再通过@Scheduled注解配置计划任务如果运行。

5.21.1. Application.java

Application.java

启用计划任务, 在Spring Boot启动类加上注解@EnableScheduling,表示该项目启用计划任务

			
package api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({ "api.config", "api.web", "api.rest", "api.service","api.schedule" })
@EnableMongoRepositories
@EnableJpaRepositories
@EnableScheduling
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}
				
			

开启计划任务 @EnableScheduling

确保你的计划任务在 @ComponentScan 包中。

5.21.2. Component

在计划任务方法上加上@Scheduled注解,表示该方法是一个计划任务,项目启动后会去扫描该注解的方法并加入计划任务列表。

			
			
package api.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
public final static long ONE_DAY = 24 * 60 * 60 * 1000;
public final static long ONE_HOUR = 60 * 60 * 1000;

public ScheduledTasks() {
// TODO Auto-generated constructor stub
}

@Scheduled(fixedRate = 5000) //5秒运行一次调度任务
public void echoCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}

@Scheduled(fixedRate = ONE_DAY)
public void scheduledTask() {
System.out.println("每隔一天执行一次调度任务");
}

@Scheduled(fixedDelay = ONE_HOUR)
public void scheduleTask2() {
System.out.println("运行完后隔一小时就执行任务");
}

@Scheduled(initialDelay = 1000, fixedRate = 5000)
public void doSomething() {
// something that should execute periodically
}

@Scheduled(cron = "0 0/1 * * * ? ")
public void ScheduledTask3() {
System.out.println(" 每隔一分钟执行一次任务");
}

}
			
			

@Scheduled参数说明

				@Scheduled注解有一些参数,用于配置计划任务执行频率,执行时段等。

				cron :cron表达式,e.g. {@code "0 * * * * ?"}从前到后依次表示秒 分 时 日 月 年
				zone:设置时区,指明计划任务运行在哪个时区下,默认为空,采用操作系统默认时区
				fixedDelay:同一个计划任务两次执行间隔固定时间,单位毫秒,上次执行结束到下次开始执行的时间,以long类型复制
				fixedDelayString:同一个计划任务两次执行间隔固定时间,单位毫秒,上次执行结束到下次开始执行的时间,以String类型赋值
				fixedRate:以一个固定频率执行,单位毫秒,表示每隔多久执行一次,以long类型赋值
				fixedRateString:以一个固定频率执行,单位毫秒,表示每隔多久执行一次,以String类型赋值
				initialDelay:延迟启动计划任务,单位毫秒,表示执行第一次计划任务前先延迟一段时间,以long类型赋值
				initialDelayString:延迟启动计划任务,单位毫秒,表示执行第一次计划任务前先延迟一段时间,以String赋值
			

5.21.3. 查看日志

				tail -f spring.log
			

5.21.4. 计划任务控制

matchIfMissing = true, 如果改属性条目不存在返回 true

				@ConditionalOnProperty("batch.metrics.export.influxdb.enabled")

				# mybean.enabled = true
				@ConditionalOnProperty(value='mybean.enabled')
				@ConditionalOnProperty(value = "endpoints.hal.enabled", matchIfMissing = true)

				# server.host = localhost
				@ConditionalOnProperty(name="server.host", havingValue="localhost")
				@ConditionalOnExpression("'${server.host}'=='localhost'")

				# spring.rabbitmq.dynamic = true
				@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
				@ConditionalOnProperty(prefix = "extension.security.cors", name = "enabled", matchIfMissing = false)
				@ConditionalOnProperty(prefix = "camunda.bpm.job-execution", name = "enabled", havingValue = "true", matchIfMissing = true)

				# spring.social.auto-connection-views = true
				@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
			

使用案例

			
package mis.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@ConditionalOnProperty("mis.schedule.enabled")
@Component
public class ScheduledTasks {
	private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
	public final static long ONE_DAY = 24 * 60 * 60 * 1000;
	public final static long ONE_HOUR = 60 * 60 * 1000;
	public final static long ONE_SECOND = 1000;

	public ScheduledTasks() {
		// TODO Auto-generated constructor stub
	}

	@Scheduled(fixedDelay = ONE_SECOND)
	public void scheduleTaskSplitLine() {
		logger.info("==================== {} ====================", dateFormat.format(new Date()));
	}
}
			
			

application.properties 配置如下

				mis.schedule.enabled=true
			




原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

目录
相关文章
|
28天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
43 0
|
8天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
24 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
10天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
【Spring系列】Sping VS Sping Boot区别与联系
|
2月前
|
XML 监控 druid
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
【Java专题_02】springboot+mybatis+pagehelper分页插件+druid数据源详细教程
|
3月前
|
Java
springboot项目打包瘦身
springboot项目打包瘦身
|
5月前
|
Java 测试技术
Springboot集成JUnit5优雅进行单元测试
Springboot集成JUnit5优雅进行单元测试
|
安全 Java Maven
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
1308 1
|
9月前
|
Java Maven
【Springboot】创建boot工程spring-boot-maven-plugin报红、出错_解决方案
【Springboot】创建boot工程spring-boot-maven-plugin报红、出错_解决方案
317 0
|
9月前
|
SQL druid 前端开发
让SpringBoot不需要Controller、Service、DAO、Mapper,卧槽!这款工具绝了!
让SpringBoot不需要Controller、Service、DAO、Mapper,卧槽!这款工具绝了!
|
11月前
|
Java C++ Spring
Spring Boot - ConfigDataEnvironmentPostProcessor(Boot 2.4)搞定配置文件加载优先级
Spring Boot - ConfigDataEnvironmentPostProcessor(Boot 2.4)搞定配置文件加载优先级
236 0