当前位置:网站首页>【无标题】
【无标题】
2022-07-02 02:24:00 【热爱Java的编程小白】
### 定时任务:
使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式:
- 一、基于注解(@Scheduled)
- 二、基于接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了。
- 三、基于注解设定多线程定时任务
#### 1.静态,基于注解:
```Java
@Configuration //标志为配置类
@EnableScheduling //开启定时任务
public class SaticScheduleTask {
//3.添加定时任务
@Scheduled(cron = "0/5 * * * * ?")
//@Scheduled(fixedRate=5000)
private void configureTasks(){
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
}
}
```
#### 2.静态,基于代码(开启和关闭):
配置类:
```Java
package com.example.timedtask.test2.config;
import com.example.timedtask.TimedTaskApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.util.concurrent.ScheduledFuture;
/**
* @Author: LiDaHu
* @Date: 2022/2/21 12:12
* @Description:
*/
@Component
@Scope("prototype")
public class DynamicTask {
private final static Logger logger = LoggerFactory.getLogger(DynamicTask.class);
private String cron;
public String name;
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;//线程池任务调度程序
private ScheduledFuture future;
public String startCron() {
cron = "0/5 * * * * ?";
System.out.println(Thread.currentThread().getName());
name = Thread.currentThread().getName();
future = threadPoolTaskScheduler.schedule(new myTask(name), new CronTrigger(cron));
TimedTaskApplication.map.put(name, future);
return "定时任务开启";
}
public String stop() {
if (future != null) {
future.cancel(true);
}
return "定时任务关闭";
}
private class myTask implements Runnable {
private String name;
myTask(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("test" + name);
...
//此处可以写等待定时任务到期所要执行的业务逻辑
}
}
}
```
Controller控制层:
```Java
@RestController
public class TimedController {
@Autowired
private DynamicTask task;
@RequestMapping("/task")
public String test() throws Exception {
// 开启定时任务,对象注解Scope是多利的。
String s = task.startCron();
System.out.println("定时任务开启");
return s;
}
@RequestMapping("/stop")
public String stop() throws Exception {
//关闭定时任务
String stop = task.stop();
System.out.println("定时任务停止");
return stop;
}
}
```
启动类:
```Java
@SpringBootApplication
public class TimedTaskApplication {
@Autowired
private static DynamicTask task;
// 线程存储器
public static ConcurrentHashMap<String, ScheduledFuture> map = new ConcurrentHashMap<String, ScheduledFuture>();
// 启动入口
public static void main(String[] args) {
SpringApplication.run(TimedTaskApplication.class, args);
}
// 创建线程
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
executor.setPoolSize(20);
executor.setThreadNamePrefix("taskExecutor-"); //设置线程名称前缀
executor.setWaitForTasksToCompleteOnShutdown(true); //设置等待任务在关机时完成
executor.setAwaitTerminationSeconds(60); //设置等待终止秒
return executor;
}
```
边栏推荐
- [C #] use regular verification content
- trading
- Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
- Is bone conduction earphone better than traditional earphones? The sound production principle of bone conduction earphones is popular science
- Golang lock
- 离婚3年以发现尚未分割的共同财产,还可以要么
- Which brand of running headphones is good? How many professional running headphones are recommended
- 【带你学c带你飞】2day 第8章 指针(练习8.1 密码开锁)
- [deep learning] Infomap face clustering facecluster
- 【带你学c带你飞】1day 第2章 (练习2.2 求华氏温度 100°F 对应的摄氏温度
猜你喜欢

Which brand of sports headset is better? Bluetooth headset suitable for sports

What is the MySQL column to row function

An analysis of circuit for quick understanding

pytest 测试框架

Leetcode face T10 (1-9) array, ByteDance interview sharing

leetcode2305. Fair distribution of biscuits (medium, weekly, shaped pressure DP)
![[reading notes] programmer training manual - practical learning is the most effective (project driven)](/img/13/28116a74512895ad725dffed02f8bd.png)
[reading notes] programmer training manual - practical learning is the most effective (project driven)

WebGPU(一):基本概念

LeetCode刷题(十)——顺序刷题46至50

RTL8189FS如何关闭Debug信息
随机推荐
【深度学习】infomap 人脸聚类 facecluster
LFM signal denoising, time-frequency analysis, filtering
Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
[C #] use regular verification content
JVM interview
[learn C and fly] 4day Chapter 2 program in C language (exercise 2.5 generate power table and factorial table
剑指 Offer 47. 礼物的最大价值
MySQL中一条SQL是怎么执行的
leetcode373. Find and minimum k-pair numbers (medium)
[graduation season] graduate seniors share how to make undergraduate more meaningful
What are the necessary things for students to start school? Ranking list of Bluetooth headsets with good sound quality
Which brand of sports headset is better? Bluetooth headset suitable for sports
附加:信息脱敏;
[learn C and fly] day 5 chapter 2 program in C language (Exercise 2)
Kibana controls es
Opencascade7.6 compilation
Deployment practice and problem solving of dash application development environment based on jupyter Lab
MySQL主从延迟问题怎么解决
No programming code technology! Four step easy flower store applet
If you want to rewind the video picture, what simple methods can you use?