淺談在springboot中使用定時(shí)任務(wù)的方式
springboot定時(shí)任務(wù)
在springboot環(huán)境下有多種方法,這里記錄下使用過(guò)的其中兩種;1、使用注解,2、通過(guò)實(shí)現(xiàn)接口的方式。
使用注解的方式雖然比較簡(jiǎn)單,但是如果項(xiàng)目需要用戶對(duì)定時(shí)周期進(jìn)行修改操作,只使用注解就比較難實(shí)現(xiàn)。所以可以使用實(shí)現(xiàn)接口的方式。通過(guò)對(duì)接口的實(shí)現(xiàn),可以在項(xiàng)目運(yùn)行時(shí)根據(jù)需要修改任務(wù)執(zhí)行周期,只需要關(guān)閉原任務(wù)再開(kāi)啟新任務(wù)即可。
1、使用注解方式
首先需要在啟動(dòng)類下添加 @EnableScheduling 注解(@EnableAsync是開(kāi)啟異步的注解)
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);
}
}
接著在需要用到定時(shí)任務(wù)的類和方法下加 @Component 和 @Scheduled(cron = "0 0/1 * * * ? ")注解,其中@Scheduled()中的 ‘cron' 有固定的格式。(@Async注解表示開(kāi)啟異步)
@Slf4j
@Component
public class AsyncTaskConfiguration {
/**
* 每分鐘檢查任務(wù)列表,判斷任務(wù)類型執(zhí)行相應(yīng)的任務(wù)
* 根據(jù)實(shí)際任務(wù)執(zhí)行情況,限定執(zhí)行任務(wù)數(shù)量
*/
@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、使用實(shí)現(xiàn)接口的方式
通過(guò)實(shí)現(xiàn) SchedulingConfigurer 接口,可對(duì)定時(shí)任務(wù)進(jìn)行操作。實(shí)現(xiàn)接口的方式相比使用注解更加靈活,但需要編寫代碼,相對(duì)繁瑣。
實(shí)現(xiàn)工具類如下:
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;
}
/**
* 添加任務(wù)
*/
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);
}
/**
* 取消任務(wù)
*/
public void cancelTriggerTask(String taskId) {
ScheduledFuture<?> future = taskFutures.get(taskId);
if (future != null) {
future.cancel(true);
}
taskFutures.remove(taskId);
getScheduledFutures().remove(future);
}
/**
* 重置任務(wù)
*/
public void resetTriggerTask(String taskId, TriggerTask triggerTask) {
cancelTriggerTask(taskId);
addTriggerTask(taskId, triggerTask);
}
/**
* 任務(wù)編號(hào)
*/
public Set<String> taskIds() {
return taskFutures.keySet();
}
/**
* 是否存在任務(wù)
*/
public boolean hasTask(String taskId) {
return this.taskFutures.containsKey(taskId);
}
/**
* 任務(wù)調(diào)度是否已經(jīng)初始化完成
*/
public boolean inited() {
return this.taskRegistrar != null && this.taskRegistrar.getScheduler() != null;
}
}
在項(xiàng)目啟動(dòng)后就自動(dòng)開(kāi)啟任務(wù)的操作類如下:
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;
/**
* 項(xiàng)目啟動(dòng)后執(zhí)行,
*/
@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("------按照預(yù)設(shè)備份周期啟動(dòng)數(shù)據(jù)庫(kù)備份定時(shí)任務(wù)");
while (!defaultSchedulingConfigurer.inited())
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
String cron = dictionnaryEntryService.getEntryValueByName("CRON_VALUE");
//默認(rèn)按照管理員用戶權(quán)限執(zhí)行備份任務(wù)
AuthLogin authLogin = authLoginService.query().eq(AuthLogin::getLogin_user, "admin").getOne();
//啟動(dòng)線程,按照原表內(nèi)的時(shí)間執(zhí)行備份任務(wù)
defaultSchedulingConfigurer.addTriggerTask("task",
new TriggerTask(
() -> System.out.println("=====----------啟動(dòng)定時(shí)任務(wù)=-----------");,
new CronTrigger(cron)));
}
}
暫停定時(shí)任務(wù):
defaultSchedulingConfigurer.cancelTriggerTask("task");
到此這篇關(guān)于淺談在springboot中使用定時(shí)任務(wù)的方式的文章就介紹到這了,更多相關(guān)springboot定時(shí)任務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Spring Boot和Kotlin的聯(lián)合開(kāi)發(fā)
這篇文章主要介紹了關(guān)于Spring Boot和Kotlin的聯(lián)合開(kāi)發(fā),需要的朋友可以參考下2017-06-06
SpringBoot如何動(dòng)態(tài)改變?nèi)罩炯?jí)別
這篇文章主要介紹了SpringBoot如何動(dòng)態(tài)改變?nèi)罩炯?jí)別,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-12-12
SpringBoot整合WebSocket的客戶端和服務(wù)端的實(shí)現(xiàn)代碼
這篇文章主要介紹了SpringBoot整合WebSocket的客戶端和服務(wù)端的實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
Springcloud Stream消息驅(qū)動(dòng)工具使用介紹
SpringCloud Stream由一個(gè)中間件中立的核組成,應(yīng)用通過(guò)SpringCloud Stream插入的input(相當(dāng)于消費(fèi)者consumer,它是從隊(duì)列中接收消息的)和output(相當(dāng)于生產(chǎn)者producer,它是發(fā)送消息到隊(duì)列中的)通道與外界交流2022-09-09

