@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. Python重学记录1

    写下这个标题觉得可笑,其实本人2014年就自学过一次python,当时看的是中谷教育的milo老师的视频,也跟着写了一些代码,只是因为当时工作上用不到也就淡忘了.不过说实话当时的水平也很低下,本来也没 ...

  2. 漫谈设计模式(二):单例(Singleton)模式

    1.前言 实际业务中,大多业务类只需要一个对象就能完成所有工作,另外再创建其他对象就显得浪费内存空间了,例如web开发中的servlet,这时便要用到单例模式,就如其名一样,此模式使某个类只能生成唯一 ...

  3. ZJNU 2201 - 挖矿谷物语

    在dfs过程中加上栈记录当次dfs走过的路径 如果当次dfs到了一个之前的dfs已经经过的点 又因为只对没有访问过的点开始dfs 所以这种情况就说明接下来不可能返回到当次dfs开始的点 将栈内元素取出 ...

  4. Maven--导出pom中依赖的jar包

    参考:https://my.oschina.net/cloudcoder/blog/212648 mvn dependency:copy-dependencies -DoutputDirectory= ...

  5. python-day7爬虫基础之Ajax数据爬取

    前几天一直在忙老师的项目,就没有继续学python,也没有写什么收获,今天晚上有空看看书,边看边理解着写吧: 首先说一下,我对Ajax的理解,就是有时候我们在浏览某个网页的时候,只要我们鼠标一直往下滑 ...

  6. Python笔记_第二篇_面向过程_第二部分_4.常用模块的简单使用_import语句的解释

    1. import语句.from...import语句.from...import*语句 解释:注意一定要在体同一级目录下 1.1 引入模块 格式:import module[,module2,... ...

  7. gcc xx -o xx

    GCG -o选项用来指定输出文件,它的用法为: [infile] -o [outfile] [infile] 表示输入文件(也即要处理的文件),它可以是源文件,也可以是汇编文件或者是目标文件:[out ...

  8. 【python】两行代码实现近百年的正反日期查询--20200202

    到2020年了.有个日期也火了,记得上一次还是2011年11月2日.为啥捏,因为日期写成数字形式 正反是一样的. 2020年也有一个这样的日期.20200202:2020年2月2日. 于是乎想写一段代 ...

  9. Python 处理图片 -- pillow库

    pip install pillow 基本使用 from PIL import Image # new 创建一张图片 im1 = Image.new('RGB', (500, 300), (50, 1 ...

  10. CaptchaCodeManager

    package org.linlinjava.litemall.wx.service; import org.linlinjava.litemall.wx.dto.CaptchaItem; impor ...