哪有什么岁月静好,不过是有人替你负重前行!

spring boot 定时任务使用

1.在Spring boot启动类上添加注解:

@EnableScheduling

2.在需要执行定时任务的类上加@Component注解,在需要执行的方法上加@Scheduled(cron = "0/2 * * * * *")注解

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

   /**
     * 每隔2秒执行一次
     */
    @Scheduled(cron = "0/2 * * * * *")
    public void task1() {
        LOGGER.info("--------------------task1开始--------------------");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LOGGER.info("--------------------task1结束--------------------");
    }
}

cron表达式格式:
{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
例 "0 0 12 ? * WED" 在每星期三下午12:00 执行(年份通常 省略)
参考:
https://blog.csdn.net/qq_38628046/article/details/113484979

posted @ 2022-08-17 15:03  pz_slider  阅读(39)  评论(0)    收藏  举报
/* 粒子吸附*/