@Scheduled默认创建的线程是单线程,任务的执行会受到上一个任务的影响,创建定时任务也比较简单

1
2
3
4
5
6
7
8
9
10
11
12
@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class ScheduledTask {
//3.添加定时任务
@Scheduled(cron = "0/5 * * * * ?")
//或直接指定时间间隔,例如:5秒
//@Scheduled(fixedRate=5000)
private void configureTasks() {
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
}
}

Cron的表达式为 秒(0-59) 分(0~59)时(0~23)日(0~31)的某天,需计算月(0~11)周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
“0/5 ?”可以解析成 每5秒执行一次,其他不指定,此时开启application,控制台没隔5秒打印一次

基于接口的定时任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer { @Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable),匿名
() -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
//2.设置执行周期(Trigger)
triggerContext -> {
return new CronTrigger("0/5 * * * * ?").nextExecutionTime(triggerContext);
}
);
}
}

多线程的定时任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Component
@EnableScheduling // 1.开启定时任务
@EnableAsync // 2.开启多线程
public class MultiThreadScheduleTask { @Async
@Scheduled(fixedDelay = 1000) //间隔1秒
public void first() throws InterruptedException {
System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "rn线程 : " + Thread.currentThread().getName());
大专栏  spring boot 创建定时任务s="line"> System.out.println();
Thread.sleep(1000 * 10);
} @Async
@Scheduled(fixedDelay = 2000)
public void second() {
System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "rn线程 : " + Thread.currentThread().getName());
System.out.println();
}
}

这个定时任务随着时间的增加不断的增加线程,这肯定会消耗大量的资源,因此在配置多线程的定时任务时,常常需要设置一个线程池来避免资源消耗过多

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@EnableAsync
@Configuration
public class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setWaitForTasksToCompleteOnShutdown(true);//设置线程在任务执行完之后才x释放
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}

使用Future来获取Runable的执行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
@Slf4j
@Component
public class Task {
public static Random random = new Random();
@Async("taskExecutor")
public Future<String> run() throws Exception {
long sleep = random.nextInt(10000);
log.info("开始任务,需耗时:" + sleep + "毫秒");
Thread.sleep(sleep);
log.info("完成任务");
return new AsyncResult<>("test");
}
}

定义超时时间并释放线程

1
2
3
4
5
6
7
8
9
10
11
12
13
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private Task task;
@Test
public void test() throws Exception {
Future<String> futureResult = task.run();
String result = futureResult.get(5, TimeUnit.SECONDS);
log.info(result);
}
}

spring boot 创建定时任务的更多相关文章

  1. Spring boot创建定时任务

    基于spring boot的应用创建定时任务不要太简单,给一个类加上@Configuration @EnableScheduling注解,然后给该类需要定时执行的方法加上@Scheduled(cron ...

  2. Spring Boot 创建定时任务(配合数据库动态执行)

    序言:创建定时任务非常简单,主要有两种创建方式:一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer). 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库 ...

  3. Spring Boot配置定时任务

    在项目开发过程中,经常需要定时任务来做一些内容,比如定时进行数据统计(阅读量统计),数据更新(生成每天的歌单推荐)等. Spring Boot默认已经实现了,我们只需要添加相应的注解就可以完成定时任务 ...

  4. Spring Kafka整合Spring Boot创建生产者客户端案例

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 创建一个kafka-producer-master的maven工程.整个项目结构如下: ...

  5. 利用spring boot创建java app

    利用spring boot创建java app 背景 在使用spring框架开发的过程中,随着功能以及业务逻辑的日益复杂,应用伴随着大量的XML配置和复杂的bean依赖关系,特别是在使用mvc的时候各 ...

  6. spring cloud教程之使用spring boot创建一个应用

    <7天学会spring cloud>第一天,熟悉spring boot,并使用spring boot创建一个应用. Spring Boot是Spring团队推出的新框架,它所使用的核心技术 ...

  7. 【spring boot】5.spring boot 创建web项目并使用jsp作前台页面

    贼烦的是,使用spring boot 创建web项目,然后我再idea下创建的,but 仅仅启动spring boot的启动类,就算整个项目都是好着的,就算是能够进入controller中,也不能成功 ...

  8. Spring Boot 创建hello world项目

    Spring Boot 创建hello world项目 1.创建项目 最近在学习Spring Boot,这里记录使用IDEA创建Spring Boot的的过程 在1出勾选,选择2,点击Next 这里填 ...

  9. 【Spring Boot】定时任务

    [Spring Boot]定时任务 测试用业务Service package com.example.schedule.service; import org.springframework.ster ...

随机推荐

  1. PAT Advanced 1044 Shopping in Mars (25) [⼆分查找]

    题目 Shopping in Mars is quite a diferent experience. The Mars people pay by chained diamonds. Each di ...

  2. java 利用管道实现线程间通信

    package com.lb; import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutpu ...

  3. linux 查看链接库的版本

    我们编译可执行文件的时候,会链接各种依赖库, 但是怎么知道依赖库的版本正确呢? 下面有几种办法: ldd 这是比较差的,因为打印结果更与位置相关 dpkg -l | grep libprotobuf ...

  4. ZJNU 2208 - 你渴望力量吗

    在图的最外面套一层0(防止到头) 然后搜索图有多少块在 '0'有两块0,一块1 '1'有一块0,一块1 其余情况不存在 #include<stdio.h> ],dx[]={,,,-},dy ...

  5. 洛谷 P3811 【模板】乘法逆元(欧拉定理&&线性求逆元)

    题目传送门 逆元定义 逆元和我们平时所说的倒数是有一定的区别的,我们平时所说的倒数是指:a*(1/a) = 1,那么逆元和倒数之间的区别就是:假设x是a的逆元,那么 a * x = 1(mod p), ...

  6. 数字格式化NumberFormat

    做财务的同学遇到逗号分隔的数值格式,会用到NumberFormat类格式化数据 BigDecimal bigDecimal = new BigDecimal("1000000000.4110 ...

  7. Cell theory|Bulk RNA-seq|Cellar heterogeneity|Micromanipulation|Limiting dilution|LCM|FACS|MACS|Droplet|10X genomics|Human cell atlas|Spatially resolved transcriptomes|ST|Slide-seq|SeqFISH|MERFISH

    生物信息学 Cell theory:7个要点 All known living things are made up of one or more cells. All living cells ar ...

  8. ios alamofire4.x网络框架url 中文问题

    一种方式是把参数放到Parameters里面 request 增加 encoding:URLEncoding.default 就可以 还有中文在path上 比如    http://www.chao. ...

  9. Linux系统国内镜像站点

    一,更换说明 第一步 备份 如centos, mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup ...

  10. redis簡單命令