@EnableScheduling
注解和@Scheduled注解實(shí)現(xiàn)定時(shí)任務(wù),也可以通過(guò)SchedulingConfigurer接口來(lái)實(shí)現(xiàn)定時(shí)任務(wù)。但是這兩種方式不能動(dòng)態(tài)添加、刪除、啟動(dòng)、停止任務(wù)。要實(shí)現(xiàn)動(dòng)態(tài)增刪啟停定時(shí)任務(wù)功能,比較廣泛的做法是集成Quartz框架。但是本人的開(kāi)發(fā)原則是:在滿足項(xiàng)目需求的情況下,盡量少的依賴其它框架,避免項(xiàng)目過(guò)于臃腫和復(fù)雜。
查看spring-context這個(gè)jar包中org.springframework.scheduling.ScheduledTaskRegistrar
這個(gè)類(lèi)的源代碼,發(fā)現(xiàn)可以通過(guò)改造這個(gè)類(lèi)就能實(shí)現(xiàn)動(dòng)態(tài)增刪啟停定時(shí)任務(wù)功能。
添加執(zhí)行定時(shí)任務(wù)的線程池配置類(lèi)
@Configuration
publicclassSchedulingConfig{
@Bean
publicTaskSchedulertaskScheduler(){
ThreadPoolTaskSchedulertaskScheduler=newThreadPoolTaskScheduler();
//定時(shí)任務(wù)執(zhí)行線程池核心線程數(shù)
taskScheduler.setPoolSize(4);
taskScheduler.setRemoveOnCancelPolicy(true);
taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-");
returntaskScheduler;
}
}
添加ScheduledFuture的包裝類(lèi)。ScheduledFuture是ScheduledExecutorService定時(shí)任務(wù)線程池的執(zhí)行結(jié)果。
publicfinalclassScheduledTask{
volatileScheduledFuture>future;
/**
*取消定時(shí)任務(wù)
*/
publicvoidcancel(){
ScheduledFuture>future=this.future;
if(future!=null){
future.cancel(true);
}
}
}
添加Runnable接口實(shí)現(xiàn)類(lèi),被定時(shí)任務(wù)線程池調(diào)用,用來(lái)執(zhí)行指定bean里面的方法。
publicclassSchedulingRunnableimplementsRunnable{
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(SchedulingRunnable.class);
privateStringbeanName;
privateStringmethodName;
privateStringparams;
publicSchedulingRunnable(StringbeanName,StringmethodName){
this(beanName,methodName,null);
}
publicSchedulingRunnable(StringbeanName,StringmethodName,Stringparams){
this.beanName=beanName;
this.methodName=methodName;
this.params=params;
}
@Override
publicvoidrun(){
logger.info("定時(shí)任務(wù)開(kāi)始執(zhí)行- bean:{},方法:{},參數(shù):{}",beanName,methodName,params);
longstartTime=System.currentTimeMillis();
try{
Objecttarget=SpringContextUtils.getBean(beanName);
Methodmethod=null;
if(StringUtils.isNotEmpty(params)){
method=target.getClass().getDeclaredMethod(methodName,String.class);
}else{
method=target.getClass().getDeclaredMethod(methodName);
}
ReflectionUtils.makeAccessible(method);
if(StringUtils.isNotEmpty(params)){
method.invoke(target,params);
}else{
method.invoke(target);
}
}catch(Exceptionex){
logger.error(String.format("定時(shí)任務(wù)執(zhí)行異常- bean:%s,方法:%s,參數(shù):%s ",beanName,methodName,params),ex);
}
longtimes=System.currentTimeMillis()-startTime;
logger.info("定時(shí)任務(wù)執(zhí)行結(jié)束- bean:{},方法:{},參數(shù):{},耗時(shí):{}毫秒",beanName,methodName,params,times);
}
@Override
publicbooleanequals(Objecto){
if(this==o)returntrue;
if(o==null||getClass()!=o.getClass())returnfalse;
SchedulingRunnablethat=(SchedulingRunnable)o;
if(params==null){
returnbeanName.equals(that.beanName)&&
methodName.equals(that.methodName)&&
that.params==null;
}
returnbeanName.equals(that.beanName)&&
methodName.equals(that.methodName)&&
params.equals(that.params);
}
@Override
publicinthashCode(){
if(params==null){
returnObjects.hash(beanName,methodName);
}
returnObjects.hash(beanName,methodName,params);
}
}
添加定時(shí)任務(wù)注冊(cè)類(lèi),用來(lái)增加、刪除定時(shí)任務(wù)。
@Component
publicclassCronTaskRegistrarimplementsDisposableBean{
privatefinalMapscheduledTasks=newConcurrentHashMap<>(16);
@Autowired
privateTaskSchedulertaskScheduler;
publicTaskSchedulergetScheduler(){
returnthis.taskScheduler;
}
publicvoidaddCronTask(Runnabletask,StringcronExpression){
addCronTask(newCronTask(task,cronExpression));
}
publicvoidaddCronTask(CronTaskcronTask){
if(cronTask!=null){
Runnabletask=cronTask.getRunnable();
if(this.scheduledTasks.containsKey(task)){
removeCronTask(task);
}
this.scheduledTasks.put(task,scheduleCronTask(cronTask));
}
}
publicvoidremoveCronTask(Runnabletask){
ScheduledTaskscheduledTask=this.scheduledTasks.remove(task);
if(scheduledTask!=null)
scheduledTask.cancel();
}
publicScheduledTaskscheduleCronTask(CronTaskcronTask){
ScheduledTaskscheduledTask=newScheduledTask();
scheduledTask.future=this.taskScheduler.schedule(cronTask.getRunnable(),cronTask.getTrigger());
returnscheduledTask;
}
@Override
publicvoiddestroy(){
for(ScheduledTasktask:this.scheduledTasks.values()){
task.cancel();
}
this.scheduledTasks.clear();
}
}
添加定時(shí)任務(wù)示例類(lèi)
@Component("demoTask")
publicclassDemoTask{
publicvoidtaskWithParams(Stringparams){
System.out.println("執(zhí)行有參示例任務(wù):"+params);
}
publicvoidtaskNoParams(){
System.out.println("執(zhí)行無(wú)參示例任務(wù)");
}
}
定時(shí)任務(wù)數(shù)據(jù)庫(kù)表設(shè)計(jì)
添加定時(shí)任務(wù)實(shí)體類(lèi)
publicclassSysJobPO{
/**
*任務(wù)ID
*/
privateIntegerjobId;
/**
*bean名稱(chēng)
*/
privateStringbeanName;
/**
*方法名稱(chēng)
*/
privateStringmethodName;
/**
*方法參數(shù)
*/
privateStringmethodParams;
/**
*cron表達(dá)式
*/
privateStringcronExpression;
/**
*狀態(tài)(1正常0暫停)
*/
privateIntegerjobStatus;
/**
*備注
*/
privateStringremark;
/**
*創(chuàng)建時(shí)間
*/
privateDatecreateTime;
/**
*更新時(shí)間
*/
privateDateupdateTime;
publicIntegergetJobId(){
returnjobId;
}
publicvoidsetJobId(IntegerjobId){
this.jobId=jobId;
}
publicStringgetBeanName(){
returnbeanName;
}
publicvoidsetBeanName(StringbeanName){
this.beanName=beanName;
}
publicStringgetMethodName(){
returnmethodName;
}
publicvoidsetMethodName(StringmethodName){
this.methodName=methodName;
}
publicStringgetMethodParams(){
returnmethodParams;
}
publicvoidsetMethodParams(StringmethodParams){
this.methodParams=methodParams;
}
publicStringgetCronExpression(){
returncronExpression;
}
publicvoidsetCronExpression(StringcronExpression){
this.cronExpression=cronExpression;
}
publicIntegergetJobStatus(){
returnjobStatus;
}
publicvoidsetJobStatus(IntegerjobStatus){
this.jobStatus=jobStatus;
}
publicStringgetRemark(){
returnremark;
}
publicvoidsetRemark(Stringremark){
this.remark=remark;
}
publicDategetCreateTime(){
returncreateTime;
}
publicvoidsetCreateTime(DatecreateTime){
this.createTime=createTime;
}
publicDategetUpdateTime(){
returnupdateTime;
}
publicvoidsetUpdateTime(DateupdateTime){
this.updateTime=updateTime;
}
}
booleansuccess=sysJobRepository.addSysJob(sysJob);
if(!success)
returnOperationResUtils.fail("新增失敗");
else{
if(sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())){
SchedulingRunnabletask=newSchedulingRunnable(sysJob.getBeanName(),sysJob.getMethodName(),sysJob.getMethodParams());
cronTaskRegistrar.addCronTask(task,sysJob.getCronExpression());
}
}
returnOperationResUtils.success();
修改定時(shí)任務(wù),先移除原來(lái)的任務(wù),再啟動(dòng)新任務(wù)
booleansuccess=sysJobRepository.editSysJob(sysJob);
if(!success)
returnOperationResUtils.fail("編輯失敗");
else{
//先移除再添加
if(existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())){
SchedulingRunnabletask=newSchedulingRunnable(existedSysJob.getBeanName(),existedSysJob.getMethodName(),existedSysJob.getMethodParams());
cronTaskRegistrar.removeCronTask(task);
}
if(sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())){
SchedulingRunnabletask=newSchedulingRunnable(sysJob.getBeanName(),sysJob.getMethodName(),sysJob.getMethodParams());
cronTaskRegistrar.addCronTask(task,sysJob.getCronExpression());
}
}
returnOperationResUtils.success();
刪除定時(shí)任務(wù)
booleansuccess=sysJobRepository.deleteSysJobById(req.getJobId());
if(!success)
returnOperationResUtils.fail("刪除失敗");
else{
if(existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())){
SchedulingRunnabletask=newSchedulingRunnable(existedSysJob.getBeanName(),existedSysJob.getMethodName(),existedSysJob.getMethodParams());
cronTaskRegistrar.removeCronTask(task);
}
}
returnOperationResUtils.success();
定時(shí)任務(wù)啟動(dòng)/停止?fàn)顟B(tài)切換
if(existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())){
SchedulingRunnabletask=newSchedulingRunnable(existedSysJob.getBeanName(),existedSysJob.getMethodName(),existedSysJob.getMethodParams());
cronTaskRegistrar.addCronTask(task,existedSysJob.getCronExpression());
}else{
SchedulingRunnabletask=newSchedulingRunnable(existedSysJob.getBeanName(),existedSysJob.getMethodName(),existedSysJob.getMethodParams());
cronTaskRegistrar.removeCronTask(task);
}
添加實(shí)現(xiàn)了CommandLineRunner接口的SysJobRunner類(lèi),當(dāng)spring boot項(xiàng)目啟動(dòng)完成后,加載數(shù)據(jù)庫(kù)里狀態(tài)為正常的定時(shí)任務(wù)。
@Service
publicclassSysJobRunnerimplementsCommandLineRunner{
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(SysJobRunner.class);
@Autowired
privateISysJobRepositorysysJobRepository;
@Autowired
privateCronTaskRegistrarcronTaskRegistrar;
@Override
publicvoidrun(String...args){
//初始加載數(shù)據(jù)庫(kù)里狀態(tài)為正常的定時(shí)任務(wù)
ListjobList=sysJobRepository.getSysJobListByStatus(SysJobStatus.NORMAL.ordinal());
if(CollectionUtils.isNotEmpty(jobList)){
for(SysJobPOjob:jobList){
SchedulingRunnabletask=newSchedulingRunnable(job.getBeanName(),job.getMethodName(),job.getMethodParams());
cronTaskRegistrar.addCronTask(task,job.getCronExpression());
}
logger.info("定時(shí)任務(wù)已加載完畢...");
}
}
}
工具類(lèi)SpringContextUtils,用來(lái)從spring容器里獲取bean
@Component
publicclassSpringContextUtilsimplementsApplicationContextAware{
privatestaticApplicationContextapplicationContext;
@Override
publicvoidsetApplicationContext(ApplicationContextapplicationContext)
throwsBeansException{
SpringContextUtils.applicationContext=applicationContext;
}
publicstaticObjectgetBean(Stringname){
returnapplicationContext.getBean(name);
}
publicstaticTgetBean(ClassrequiredType) {
returnapplicationContext.getBean(requiredType);
}
publicstaticTgetBean(Stringname,ClassrequiredType) {
returnapplicationContext.getBean(name,requiredType);
}
publicstaticbooleancontainsBean(Stringname){
returnapplicationContext.containsBean(name);
}
publicstaticbooleanisSingleton(Stringname){
returnapplicationContext.isSingleton(name);
}
publicstaticClass?extends?Object>getType(Stringname){
returnapplicationContext.getType(name);
}
}
本文完,參考本文代碼可成功運(yùn)行,親測(cè)!
(感謝閱讀,希望對(duì)你所有幫助)來(lái)源:www.jianshu.com/p/0f68936393fd-
源代碼
+關(guān)注
關(guān)注
96文章
2945瀏覽量
66748 -
spring
+關(guān)注
關(guān)注
0文章
340瀏覽量
14344 -
Boot
+關(guān)注
關(guān)注
0文章
149瀏覽量
35839 -
SpringBoot
+關(guān)注
關(guān)注
0文章
173瀏覽量
179
原文標(biāo)題:告別硬編碼,SpringBoot實(shí)現(xiàn)動(dòng)態(tài)增刪啟停定時(shí)任務(wù)
文章出處:【微信號(hào):AndroidPush,微信公眾號(hào):Android編程精選】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論