springboot 定时任务基础模板

springboot 如何开启定时任务

基础版本
一、在启动类上面加上 @EnableScheduling 即可开启定时
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class ScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication .class, args);
    }
}
二、创建定时任务类
@Component
@Slf4j
public class WorkbenchProgressStatJob {


    @Autowired
    WorkbenchProgressService workbenchProgressService;


    @Scheduled(cron = "0 0 9,12,18 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void doStatJob()  {

        log.info("===============  WorkbenchProgressStatJob start at {} ===============", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        
        log.info("===============  WorkbenchProgressStatJob end at {} ===============", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
    }
}

我这里演示的是每天 9点、12点、18点执行一次任务,所以 在 @Scheduler注解里面使用了 cron表达式
0 0 9,12,18 * * ?

这里看到的 @Scheduled注解,不止可以用cron参数 也可以使用 fixedDelay() 或者 fixedRate() 参数,

fixedDelay() : 以固定时间间隔来分割上一次任务执行和下一次任务执行。 也就是上一次任务执行完成之后,开始计算时间,时间达到设置的数字, 开始下一次任务执行。 毫秒为单位

fixedRate(): 以固定时间间隔来分割每一次的任务调用,这里和上一个有区别的地方是,他不会等到上一次任务执行结束才开始计算时间, 而是上一次任务执行开始,就开始计算。 如果任务执行耗时比较长,设置的时间间隔比较短,那么可能上一次还没执行玩,第二次已经开始。

多线程进阶版

前面的基础版本是单线程,如果有多个定时任务,其中一个任务耗时比较长,那么其他的任务就会被卡住,可能无法达到预期的定时执行的效果。
这个时候,给任务加上多线程,就能避免这个问题了。

新增多线程配置类
@Configuration
@EnableAsync
public class ExecutorConfig {

    @Bean("taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(20);
        taskExecutor.setQueueCapacity(20);
        taskExecutor.setKeepAliveSeconds(60);
        taskExecutor.setThreadNamePrefix("taskExecutor-schedule-");
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        return taskExecutor;
    }
}
在定时任务上添加注解 @Async
    @Scheduled(fixedDelay = 1000)
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void doStatJob1() throws InterruptedException {
        log.info("doStatJob1 start");
        Thread.sleep(10000);
        log.info("doStatJob1 end");
    }

这样这个定时任务会提交到线程池中去执行,如果有多个一样的任务同事执行,只要没有把线程池占慢 都可以执行下去。
如果每个定时任务都想多线程执行,那么直接将 @Async注解提取到 定时任务配置类的类上面去就可以了。

模拟测试

基础版:

	 @Scheduled(fixedDelay = 1000)
    @Transactional(rollbackFor = Exception.class)
    public void doStatJob1() throws InterruptedException {
        log.info("doStatJob1 start");
        Thread.sleep(10000);
        log.info("doStatJob1 end");
    }


    @Scheduled(fixedDelay = 1000)
    @Transactional(rollbackFor = Exception.class)
    public void doStatJob2() throws InterruptedException {
        log.info("doStatJob2 start");
        Thread.sleep(10000);
        log.info("doStatJob2 end");
    }

结果:
在这里插入图片描述

多线程版:

    @Scheduled(fixedDelay = 1000)
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void doStatJob1() throws InterruptedException {
        log.info("doStatJob1 start");
        Thread.sleep(10000);
        log.info("doStatJob1 end");
    }


    @Scheduled(fixedDelay = 1000)
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void doStatJob2() throws InterruptedException {
        log.info("doStatJob2 start");
        Thread.sleep(10000);
        log.info("doStatJob2 end");
    }

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 好的,我可以为您提供一段 Vue 3 中的模糊查询代码。 首先,您需要在模板中添加一个输入框,并为其绑定一个响应式数据,例如 `query`: ```html <template> <input v-model="query" placeholder="请输入查询关键字" /> </template> ``` 然后,您可以使用 computed 属性来计算出符合查询条件的数据,例如: ```js <script> export default { ### 回答2: 在Spring Boot中使用定时任务非常简单,只需要遵循以下步骤: 1. 添加依赖:在pom.xml文件中添加Spring Boot的定时任务依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 2. 创建一个定时任务类:在你的Java包中创建一个继承自`org.springframework.scheduling.annotation.Scheduled`的类。 ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyScheduledTask { // 每天12点执行一次定时任务 @Scheduled(cron = "0 0 12 * * ?") public void doTask() { // 执行你的定时任务逻辑 System.out.println("定时任务执行中..."); } } ``` 3. 启用定时任务:在你的Spring Boot应用主类或配置类上添加`@EnableScheduling`注解以启用定时任务。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 上述代码展示了一个简单的定时任务,在每天的12点执行一次。你可以根据需要修改`@Scheduled`注解的cron表达式来调整定时任务的执行时间。 通过这种方式,你可以轻松地在Spring Boot项目中使用定时任务。 ### 回答3: 下面是一个使用Spring Boot的定时任务代码示例: 1. 首先,确保你的项目中已经引入了Spring Boot的相关依赖。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 2. 创建一个定时任务类,比如`MyTask`,并使用`@Component`注解将其纳入Spring容器管理: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask { @Scheduled(fixedRate = 1000) // 每隔1秒执行一次定时任务 public void doTask() { // 定时任务要执行的逻辑代码 System.out.println("Hello, World!"); } } ``` 3. 在Spring Boot应用的主类中,添加`@EnableScheduling`注解启用定时任务的功能: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } ``` 这样,定时任务就会在应用启动后每隔1秒执行一次`MyTask`类中的`doTask`方法。你可以根据需要修改注解`@Scheduled`的参数,比如设置固定的延迟时间、定时执行的时间表达式等。 注意:在使用定时任务时,需要确保项目中已经启用了Spring的定时任务功能。你可以在应用的配置文件(比如application.properties或application.yml)中添加以下配置: ```yaml spring: task: scheduling: enabled: true ``` 这样就完成了Spring Boot使用定时任务的代码。希望能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值