springboot开启定时任务


SpringBoot开启定时任务

1.首先在启动类XXXApplication上添加@EnableSchedule注解

@SpringBootApplication
@EnableScheduling
public class DemoApplication {
    ......
}

2.然后添加如下的类,自行改造即可

这个类里面比较重要的注解:@Scheduled,里面需要一个cron表达式需要自己写,推荐一个网站可以自动生成这个时间表达式:https://cron.qqe2.com/

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

@Async
@Component
public class DemoSchedule {
    private static final Logger logger = LoggerFactory.getLogger(DemoSchedule.class);
    
    //这里可以注入各种Service,Mapper等bean对象

    /**
     * 每分钟的第3秒执行这个定时任务
     * 如果需要其他时间执行请联系项目经理
     */
    @Scheduled(cron = "3 * * * * ?")
    public void demoSchedule(){
        logger.debug("定时任务开始执行");
    }
}


免责声明!

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



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