Spring Task实现简单的定时任务

在日常的开发中,我们常常回用到定时功能,目前简单一点的就是,Spring项目的Spring Task;然后复杂点的就是Quartz。

1. 简单的Spring Task

如果我们的项目中的定时任务,只是简单是在固定时间执行批量任务,就可以使用Spring Task来实现。
现在初始一个Spring boot项目,添加依赖:

<!-- Lombok 自动生成getter和setter等bean中方法 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

相当简单的使用:

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

// 注入log
@Slf4j
@Component
// 开启注解定时任务的支持
@EnableScheduling
public class DemoTask {

    // cron表达式
    @Scheduled(cron = "0/1 * * * * *")
    public void scheduled() throws Exception {
        // 任务内容
        log.info("=====>>>>> 开始定时任务 {}", System.currentTimeMillis());
        Thread.sleep(2000);
        System.out.println("完成定时任务");
    }
}

然后开启项目,这样我们的一个定时任务就开始了:

2. cron表达式

cron表达式是用来描述一个定时任务的执行时间的,具体书写规则:
我也没理清,没得时间,我们可以去http://qqe2.com/cron/index手动配置即可,方便好用

3. 开启多线程的定时任务

1). 添加异步调用配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

// 异步调用配置,主要用于开启多线程的定时任务
@Configuration
@EnableAsync
public class AsyncConfig {
    // 此处成员变量应该使用@Value从配置中读取
    private int corePoolSize = 10;
    private int maxPoolSize = 200;
    private int queueCapacity = 10;
    @Bean("taskAsync")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}

2). 在需要多线程的类或者方法上使用@Async开启多线程

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

// 注入log
@Slf4j
@Component
// 开启注解定时任务的支持
@EnableScheduling
public class DemoTask {

    // cron表达式
    @Async("taskAsync")
    @Scheduled(cron = "0/1 * * * * *")
    public void scheduled() throws Exception {
        // 任务内容
        log.info("=====>>>>> 开始定时任务 {}", System.currentTimeMillis());
        Thread.sleep(2000);
        System.out.println("完成定时任务");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值