SpringBoot定时任务

SpringBoot定时任务步骤

  1. 在项目启动类上面添加注解 @EnableScheduling
  2. 使用定时注解 @Scheduled
@ComponentScan("com.zhondu.xxxx")
@MapperScan("com.zhondu.xxxx.mapper")
@SpringBootApplication
@EnableScheduling 
public class WikiApplication {
    private static final Logger logger = LoggerFactory.getLogger(WikiApplication.class);

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(WikiApplication.class);
        ConfigurableEnvironment environment = application.run(args).getEnvironment();
        logger.info("项目启动成功");
        logger.info("地址和端口:http://127.0.0.1:{}",environment.getProperty("server.port"));
    }

}
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;

/**
 * @ClassName TestJob
 * @Description TODO
 * @Author wuning
 * @Date 2023/3/19 16:15
 * @Version 1.0
 */
@Component
public class TestJob {
    private static final Logger LOG = LoggerFactory.getLogger(TestJob.class);

    /**
     * 固定时间间隔,fixedRate单位毫秒
     */
    @Scheduled(fixedRate = 1000)
    public void simple() throws InterruptedException {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String dateString = formatter.format(new Date());
        Thread.sleep(2000);
        LOG.info("每隔5秒钟执行一次: {}", dateString);
    }

    /**
     * 自定义cron表达式跑批
     * 只有等上一次执行完成,下一次才会在下一个时间点执行,错过就错过
     */
    @Scheduled(cron = "*/1 * * * * ?")
    public void cron() throws InterruptedException {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss SSS");
        String dateString = formatter.format(new Date());
        Thread.sleep(1500);
        LOG.info("每隔1秒钟执行一次: {}", dateString);
    }
}

你可能感兴趣的:(spring,boot)