springboot定时器和java.util.Time定时器 使用总结

springboot 定时器使用
1.在启动类添加定时器启动注解

@SpringBootApplication
@EnableTransactionManagement
@EnableScheduling//启动定时器

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

2.创建一个类 使用 @Scheduled(cron = “xxxxxx”)在方法上就能够启动定时器
cron 表达式生成器

@Component
public class TimerTask {
    private static final Logger log = LogManager.getLogger(TimerTask.class);
  

    @Autowired
    private CourseInfolmpl courseInfolmpl;
    //定时器测试
    @Scheduled(cron = "0/2 * * * * ? ")// 间隔2秒执行
    public void testTimerTask(){
        log.info("定时器测试");
    }

java.util.Timer; 定时器

//每天在凌晨2点执行
public void clearCache() {
		Timer timer = new Timer();
		//Calendar这个专门用于对日期进行操作的类
		Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 02);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date time = calendar.getTime();
        
        timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {
				// 设置支持任务

			}
		}, time, 1000 * 60 * 60 * 24); //第一个参数是几时执行 第二个参数是执行周期
	}
	

timer.schedule也能够执行定时任务

两个方法的区别是 如果中间出现问题scheduleAtFixedRate会按照原来的时间完成 而schedule这不会按照原来时间完成 而是要超时完成

发布了78 篇原创文章 · 获赞 5 · 访问量 7377

猜你喜欢

转载自blog.csdn.net/weixin_41930050/article/details/103036215
今日推荐