springboot-定时任务
everthing will be okay....
实现结果如下:
- 添加依赖包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
-
添加相关注释
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
-
定时任务实现(CRON表达式与自定义时间)
package com.empirefree.component; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @ProjectName: SchedulerTask * @Package: com.empirefree.component * @Description: * @Author: huyuqiao * @CreateDate: 2020/10/12 16:01 */ @Component public class SchedulerTask { private int count=0; @Scheduled(cron="*/6 * * * * ?") private void process(){ System.out.println("this is scheduler task runing "+(count++)); } }
package com.empirefree.component; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * @ProjectName: Scheduler2Task * @Package: com.empirefree.component * @Description: * @Author: huyuqiao * @CreateDate: 2020/10/12 16:01 */ @Component public class Scheduler2Task { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 6000) public void reportCurrentTime() { System.out.println("现在时间:" + dateFormat.format(new Date())); } }