浅谈在springboot中使用定时任务的方式
作者:拍打醒 发布时间:2023-03-02 19:14:09
标签:springboot,定时任务
springboot定时任务
在springboot环境下有多种方法,这里记录下使用过的其中两种;1、使用注解,2、通过实现接口的方式。
使用注解的方式虽然比较简单,但是如果项目需要用户对定时周期进行修改操作,只使用注解就比较难实现。所以可以使用实现接口的方式。通过对接口的实现,可以在项目运行时根据需要修改任务执行周期,只需要关闭原任务再开启新任务即可。
1、使用注解方式
首先需要在启动类下添加 @EnableScheduling 注解(@EnableAsync是开启异步的注解)
package com.fongtech.cli;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@MapperScan("com.fongtech.cli.mbg.*.**")
@EnableAsync
@EnableScheduling
public class SpringbootAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAdminApplication.class, args);
}
}
接着在需要用到定时任务的类和方法下加 @Component 和 @Scheduled(cron = "0 0/1 * * * ? ")注解,其中@Scheduled()中的 ‘cron' 有固定的格式。(@Async注解表示开启异步)
@Slf4j
@Component
public class AsyncTaskConfiguration {
/**
* 每分钟检查任务列表,判断任务类型执行相应的任务
* 根据实际任务执行情况,限定执行任务数量
*/
@Scheduled(cron = "0 0/1 * * * ? ")
@Async
public void startCommonTask() throws Exception {
log.info("startCommonTask start........." + Thread.currentThread().getName());
commonTaskService.startCommonTask();
log.info("startCommonTask end........." + Thread.currentThread().getName());
}}
2、使用实现接口的方式
通过实现 SchedulingConfigurer 接口,可对定时任务进行操作。实现接口的方式相比使用注解更加灵活,但需要编写代码,相对繁琐。
实现工具类如下:
package com.fongtech.cli.admin.tasktime;
import com.fongtech.cli.common.util.BeanUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.SchedulingException;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
/**
* @author linb
* @date 2020/6/15 11:16
*/
@Configuration
//@EnableScheduling
public class DefaultSchedulingConfigurer implements SchedulingConfigurer {
private ScheduledTaskRegistrar taskRegistrar;
private Set<ScheduledFuture<?>> scheduledFutures = null;
private Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<>();
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
this.taskRegistrar = taskRegistrar;
}
@SuppressWarnings("unchecked")
private Set<ScheduledFuture<?>> getScheduledFutures() {
if (scheduledFutures == null) {
try {
// spring版本不同选用不同字段scheduledFutures
scheduledFutures = (Set<ScheduledFuture<?>>) BeanUtils.getProperty(taskRegistrar, "scheduledTasks");
} catch (NoSuchFieldException e) {
throw new SchedulingException("not found scheduledFutures field.");
}
}
return scheduledFutures;
}
/**
* 添加任务
*/
public void addTriggerTask(String taskId, TriggerTask triggerTask) {
if (taskFutures.containsKey(taskId)) {
throw new SchedulingException("the taskId[" + taskId + "] was added.");
}
TaskScheduler scheduler = taskRegistrar.getScheduler();
ScheduledFuture<?> future = scheduler.schedule(triggerTask.getRunnable(), triggerTask.getTrigger());
getScheduledFutures().add(future);
taskFutures.put(taskId, future);
}
/**
* 取消任务
*/
public void cancelTriggerTask(String taskId) {
ScheduledFuture<?> future = taskFutures.get(taskId);
if (future != null) {
future.cancel(true);
}
taskFutures.remove(taskId);
getScheduledFutures().remove(future);
}
/**
* 重置任务
*/
public void resetTriggerTask(String taskId, TriggerTask triggerTask) {
cancelTriggerTask(taskId);
addTriggerTask(taskId, triggerTask);
}
/**
* 任务编号
*/
public Set<String> taskIds() {
return taskFutures.keySet();
}
/**
* 是否存在任务
*/
public boolean hasTask(String taskId) {
return this.taskFutures.containsKey(taskId);
}
/**
* 任务调度是否已经初始化完成
*/
public boolean inited() {
return this.taskRegistrar != null && this.taskRegistrar.getScheduler() != null;
}
}
在项目启动后就自动开启任务的操作类如下:
package com.fongtech.cli.admin.tasktime;
import com.fongtech.cli.admin.service.IAuthLoginService;
import com.fongtech.cli.admin.service.IBackupsService;
import com.fongtech.cli.admin.service.IDictionnaryEntryService;
import com.fongtech.cli.mbg.model.entity.AuthLogin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
/**
* 项目启动后执行,
*/
@Slf4j
@Component
@Order(value = 1)
public class CmdRunner implements CommandLineRunner {
@Autowired
private DefaultSchedulingConfigurer defaultSchedulingConfigurer;
@Autowired
private IDictionnaryEntryService dictionnaryEntryService;
@Autowired
private IBackupsService backupsService;
@Autowired
private IAuthLoginService authLoginService;
@Override
public void run(String... args) throws Exception {
log.info("------按照预设备份周期启动数据库备份定时任务");
while (!defaultSchedulingConfigurer.inited())
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
String cron = dictionnaryEntryService.getEntryValueByName("CRON_VALUE");
//默认按照管理员用户权限执行备份任务
AuthLogin authLogin = authLoginService.query().eq(AuthLogin::getLogin_user, "admin").getOne();
//启动线程,按照原表内的时间执行备份任务
defaultSchedulingConfigurer.addTriggerTask("task",
new TriggerTask(
() -> System.out.println("=====----------启动定时任务=-----------");,
new CronTrigger(cron)));
}
}
暂停定时任务:
defaultSchedulingConfigurer.cancelTriggerTask("task");
来源:https://blog.csdn.net/iampatrick_star/article/details/117930163
0
投稿
猜你喜欢
- SingleClick:@Retention(AnnotationRetention.RUNTIME)@Target(AnnotationT
- 前言在实际开发中我们经常会与时间打交道,那这就会涉及到一个时间格式转换的问题。接下来会介绍几种在SpirngBoot中如何对时间格式进行转换
- 通常情况下我们想实现文字的走马灯效果需要在xml文件中这样设置<TextView android:layout_widt
- Spring Boot1.为什么要使用 Spring Boot因为Spring, SpringMVC 需要使用的大量的配置文件 (xml文件
- 本文实例为大家分享了JavaFX实现简单日历效果的具体代码,供大家参考,具体内容如下1.先看效果:2.代码:1)ClockEdge.java
- 公司有个业务需要查出所有的用户权限分类,并将最后一层类别所包含的权限查出来。数据库说明,有一个parent_id 字段是最好的:、paren
- 最近做的一个小项目中有这样的需求:整个项目有一份config.json保存着项目的一些配置,是存储在本地文件的一个资源,并且应用中存在读写(
- 本文实例为大家分享了flutter实现底部导航栏的具体代码,供大家参考,具体内容如下一.flutter底部导航栏常用组件BottomNavi
- Struts2简介Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts
- 本文实例讲述了C#推送信息到APNs的方法。分享给大家供大家参考。具体实现方法如下:class Program{ public
- 各位亲们可以尝试以下代码:注:这里我就只有一个html标签对来说明问题了,首部之类的东西,自己添加。<html> &n
- 我们先来看本地如何生成图片验证码的,再来写输出到网页的验证码如何实现。先来看最简单的—实现的功能是,将一个字符串变成图片写入到文件中实现代码
- 1.实例1(主要看到[2])1.1.系统功能: 开发一个计算器服务CalculateService,这个服务包含加(plus)、减(minu
- 我就废话不多说了,大家还是直接看代码吧!public static String mapToTxt(Map<String,String
- 一、获取接口请求的数据可以在Interceptor的afterCompletion中实现但是要重写RequestWrapper代码记录如下:
- 当你使用synchronized关键字的时候,是通过互斥器来保障线程安全以及对共享资源的同步访问。线程间也经常需要更进一步的协调
- 引言一个复杂的分布式系统,用户发起一个请求,这个请求可能调用几十到几百个服务,经过很多业务层,而每个业务又是多个机器集群,一个请求具体被随机
- 前言:对于一个程序员来说,尤其是在java web端开发的程序员,三大框架:Struts+Hibernate+Spring是必须要掌握熟透的
- c#开发cad如何预览图块1.定义变量的方法代码如下2. 获取GetDwgImag图像的方法代码3.实现显示DWG文件的方法代码方
- [LeetCode] 3. Longest Substring Without Repeating Characters 最长无重复字符的子