@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. Android巩固之事件分发机制

    https://www.cnblogs.com/liaojie970/p/5869152.html onTouchEvent是真正用来进行业务逻辑处理的地方,返回true表示已经将该事件消费,返回fa ...

  2. PAT Basic 完美数列(25) [two pointers]

    题目 给定⼀个正整数数列,和正整数p,设这个数列中的最⼤值是M,最⼩值是m,如果M <= m * p,则称这个数列是完美数列.现在给定参数p和⼀些正整数,请你从中选择尽可能多的数构成⼀个完美数列 ...

  3. Python中的encode和decode

    原文地址:http://www.cnblogs.com/tingyugetc/p/5727383.html 1.Python3中对文本和二进制数据进行了比较清晰的区分,文本总是 unicode ,由  ...

  4. Python KNN 学习曲线

    学习曲线的目的是选择更好的模型参数.以最近邻算法为例,选取最近的多少个数据点,才能达到最优.可以控制训练集不动,调整最近的点的个数,绘制学习曲线. import matplotlib.pyplot a ...

  5. MySQL--存储引擎的特性

    常用存储引擎的对比 特点 MyISAM InnoDB MEMORY MERGE NDB 存储限制 有 64TB 有 没有 有 事务安全   支持       锁机制 表锁 行锁 表锁 表锁 行锁 B树 ...

  6. JS控制 input 输入字符限制全搜集

    ENTER键可以让光标移到下一个输入框 <input onkeydown="if(event.keyCode==13)event.keyCode=9" > 只能是中文 ...

  7. jackson解析处理JSON

    package com.ruoyi.common.json; import java.io.File; import java.io.IOException; import java.io.Input ...

  8. 吴裕雄--天生自然 pythonTensorFlow图形数据处理:循环神经网络预测正弦函数

    import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 定义RNN的参数. HIDDEN_SIZE = ...

  9. F - Filter Gym - 100553F (bitset用法)

    题目链接:http://codeforces.com/gym/100553/attachments/download/2885/20142015-acmicpc-northeastern-europe ...

  10. G. Petya and Graph(经典项目与项目消耗问题)(网络流)

    题:https://codeforces.com/contest/1082/problem/G 题意:给定有边权和点权的图,问你选一些边,然sum边-sum点最大(点权被多次用为公共点只会减一次) 分 ...