@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. sublime text2设置快捷键打开浏览器

    1 编辑一个py文件,内容如下: import sublime, sublime_plugin import webbrowser url_map = { 'C:\\server\\www\\' : ...

  2. VirtualBox虚拟机下Linux CentOS6.9安装增强功能

     VirtualBox安装CentOS后,再安装增强功能就可以共享文件夹.粘贴板以及鼠标无缝移动,主要步骤如下: 1.yum -y update 2.yum -y install g++ gcc gc ...

  3. python中的变量对象小结2

    # .变量名和数据内容是分开存储的. # .数据保存在内存中的一个位置(地址). # .变量中保存着数据在内存中的地址. # 引用就是变量中记录数据的地址. #不可变变量,重新赋值时会重新开辟一个地址 ...

  4. Python笔记_第四篇_高阶编程_GUI编程之Tkinter_1.使用Python进行GUI编程的概述

    1. GUI概述: GUI全称为Graphical User Interface,叫做图形用户界面,也是一种交互方式(Interaction).早期计算机使用的命令行界面(command-line i ...

  5. 通过Dockerfile 文件为linux images 添加新用户

    要求: (1)增加一个新用户,名为mynewuser (2)让这个用户有root权限 (3)设置其密码为mynewpassword (4)Container启动后以mynewuser登录,并且直接到m ...

  6. 学习spring第二天

    Spring第二天笔记 1. 使用注解配置Spring入门 1.1. 说在前面 学习基于注解的IoC配置,大家脑海里首先得有一个认知,即注解配置和xml配置要实现的功能都是一样的,都是要降低程序间的耦 ...

  7. 对《The future of ReactiveCocoa》的一些思考

    前言 我以为 第一次接触 swift 语言时,看到函数的表示形式如下: func fun(num: Int) -> Int { return num + 1 } let f = fun(1) 和 ...

  8. Codeforces Round #517 (Div. 2)(1~n的分配)

    题:https://codeforces.com/contest/1072/problem/C 思路:首先找到最大的x,使得x*(x+1)/2 <= a+b 那么一定存在一种分割使得 a1 &l ...

  9. 关于前端JS的总结

    简介 JavaScript是一种计算机编程语言,可以像等其他编程语言那样定义变量,执行循环等.主要执行在浏览器上,为HTML页面提供动态效果,而且JavaScript是一种脚本语言,它的代码是解释执行 ...

  10. 2019-ECfinal-M题-value

    题目传送门 sol:每个下标都有选和不选两种情况,所以总方案数是$2^{n}$,在$n$最大是$100000$的情况下不符合要求.可以这样想,假设$i^{p}=k$有符合题目要求的解,还有一个整数$j ...