Spring Boot笔记(六) springboot 集成 timer 定时任务


个人博客网:https://wushaopei.github.io/    (你想要这里多有)

1、创建具体要执行的任务类:

package com.example.poiutis.timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.TimerTask; /** * @ClassName MyTimeTask * @Description TODO * @Author wushaopei * @Date 2019/7/26 15:55 * @Version 1.0 */ public class MyTimeTask extends TimerTask{ private static Logger logger = LoggerFactory.getLogger(MyTimeTask.class); private String name; public MyTimeTask(String inputName){ name = inputName; } @Override public void run() { //打印当前name 的内容 System.out.println("Current exec name is " + name); logger.info(System.currentTimeMillis()+"111"); } public String getName() { return name; } public void setName(String name) { this.name = name; } } 

run()方法中是要执行的任务代码,定时器启动时会执行 run() 方法中的业务逻辑 ;

2、创建 timer 的 实例工作类:

package com.example.poiutis.timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.Trigger; import java.sql.Time; import java.util.Timer; /** * @ClassName MyTimer * @Description TODO * @Author wushaopei * @Date 2019/7/26 15:57 * @Version 1.0 */ @Configuration public class MyTimer { // public static void main(String[] args) { @Bean public void testQuartzTrigger1() { //1.创建一个timer实例 Timer timer = new Timer(); //2.创建一个MyTimerTask实例 MyTimeTask myTimeTask = new MyTimeTask("No.1"); //3.通过timer定时定频率调用myTimerTask的业务逻辑 // 即 第一次执行是在当前时间的两秒之后,之后每隔一秒钟执行一次\ timer.schedule(myTimeTask,2000L,1000L); } } 

添加@Configuration  注解,自动注入实例对象,并由springboot 启动 定时器,执行任务。

注意: 使用springboot 时保证包扫描路径是正确的;

执行效果:

GitHub

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM