1.创建spring boot项目,在pom.xml添加依赖:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--定时器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>
2.启动类启动定时:
/** * 启动类 */ @SpringBootApplication //开启定时 @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
3.创建定时任务实现类:
/** * 定时任务类1 * Created by ASUS on 2018/5/6 * * @Authod Grey Wolf */ //要声明为bean,没有声明启动类启动无法实现定时效果 @Component public class SchedulerTask { private int count=0; //表示每隔6秒打印一次 @Scheduled(cron = "*/6 * * * * ?") private void proces(){ System.out.println("this is a scheduler task running:"+(count++)); } }
/** * 定时任务类2 * Created by ASUS on 2018/5/6 * * @Authod Grey Wolf */ //要声明为bean,没有声明启动类启动无法实现定时效果 @Component public class Scheduler2Task { private static final SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss"); //表示每隔6秒打印一次 @Scheduled(fixedRate = 6000) public void reportCurrentTime(){ System.out.println("现在时间:"+dataFormat.format(new Date())); } }
4.run启动类application.class 测试效果:
参数说明
@Scheduled
参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?"
,一种是 fixedRate = 6000
,两种都表示每隔六秒打印一下内容。
fixedRate 说明
@Scheduled(fixedRate = 6000)
:上一次开始执行时间点之后6秒再执行@Scheduled(fixedDelay = 6000)
:上一次执行完毕时间点之后6秒再执行@Scheduled(initialDelay=1000, fixedRate=6000)
:第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次