0
点赞
收藏
分享

微信扫一扫

springboot项目创建定时任务,如何使用@Scheduled注解实现定时任务


可以使用@Scheduled注解实现定时任务。步骤入下:

1.在启动类上加上@EnableScheduling开启定时任务,具体的代码如下:

springboot项目创建定时任务,如何使用@Scheduled注解实现定时任务_spring

2.创建定时任务类

package com.yangjunbo.JPADemo.scheduled;

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

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


@Component
public class SchedulerTask {
private static final Logger logger = LoggerFactory.getLogger(SchedulerTask.class);

@Scheduled(cron="*/10 * * * * ?")
private void taskCron(){
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
logger.info("现在时间Scheduled1: " + dateFormat.format(new Date()));
}
//在上面的示例中,创建了taskCron的定时任务,然后在taskCron()方法中增加了@Scheduled注解设置Cron表达式,设置任务每隔10秒执行一次。//@Scheduled不仅支持以Cron表达式的方式定义执行周期,还支持以固定时间间隔的方式调度任务。下面定义一个固定时间间隔执行的任务,具体的代码如下:

@Scheduled(fixedRate = 10000)
public void taskFixed() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
logger.info("现在时间Scheduled2: " + dateFormat.format(new Date()));
}
//在上面的示例中,使用fixedRate参数就是指固定的时间间隔,单位是毫秒,即设置任务每隔10秒执行一次。
}

springboot项目创建定时任务,如何使用@Scheduled注解实现定时任务_mybatis_02

3.启动项目查看日志的输出

springboot项目创建定时任务,如何使用@Scheduled注解实现定时任务_spring boot_03

后台日志显示,SchedulerTask任务每隔10秒输出当前时间,说明定义的任务正在后台定时执行。

参考书籍《springboot从入门到实战-章为忠著》


举报

相关推荐

0 条评论