1. 程式人生 > 其它 >spring管理定時任務,實現網頁新增,停用,檢視定時任務的功能

spring管理定時任務,實現網頁新增,停用,檢視定時任務的功能

選用Quartz進行開發,用oracle進行持久化。來實現頁面新增、檢視定時任務等功能。

1、首先需要建立Quratz所需要的資料庫表結構,借鑑博主:四夕月的文章https://www.cnblogs.com/yueUyueMe/p/14648751.html

2、配置quartz.properties配置檔案。

#排程器名稱
org.quartz.scheduler.instanceName = TechheroScheduler

#如果使用叢集,instanceId必須唯一,設定成AUTO
org.quartz.scheduler.instanceId = AUTO

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 3
org.quartz.threadPool.threadPriority = 1
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
#表示實際執行時間與下一次應該執行時間之間的差值,超過這個差值就不會彌補執行,低於這個差值就會彌補執行
org.quartz.jobStore.misfireThreshold = 5000

#是否使用叢集
org.quartz.jobStore.isClustered = true

# jobStore 持久化配置
#儲存方式使用JobStoreTX,也就是資料庫
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# 使用quartz.properties,不使用預設配置
org.quartz.jobStore.useProperties = false
#資料庫中quartz表的表名字首
org.quartz.jobStore.tablePrefix = QRTZ_

#配置資料來源
#org.quartz.jobStore.dataSource = qzDS
#org.quartz.dataSource.qzDS.provider = hikaricp
#org.quartz.dataSource.qzDS.driver = oracle.jdbc.driver.OracleDriver
#org.quartz.dataSource.qzDS.URL = jdbc:oracle:thin:@47.104.80.42:521:orcl
#org.quartz.dataSource.qzDS.user = cloud2
#org.quartz.dataSource.qzDS.password = root
#org.quartz.dataSource.qzDS.validationQuery = select 1 from dual

3、建立定時任務的實體類來記錄定時任務的資訊。
@EqualsAndHashCode(callSuper = false)
@Data
public class JobConfigDTO implements Serializable {

private static final long serialVersionUID = -9046008904285626159L;

@ApiModelProperty(value = "任務名稱")
private String jobName;

@ApiModelProperty(value = "任務所屬組")
private String groupName;

@ApiModelProperty(value = "任務執行類")
private String jobClass;

@ApiModelProperty(value = "任務排程時間cron表示式")
private String cronExpression;

@ApiModelProperty(value = "任務描述")
private String description;

@ApiModelProperty(value = "附加引數")
private Map<String, Object> param;

}

4、編寫建立和查詢等測試類。
新增定時任務:
  • 新增定時任務Job:
public class MonitorSystemSchedule implements Job {

private static final Logger logger = LoggerFactory.getLogger(MonitorSystemSchedule.class);

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");

@Autowired
private SysMonitorService sysMonitorService;
@Autowired
private SysWarningService sysWarningService;

private static final double NCSYLYZ=0.8;
private static final double CPUSYLYZ=0.8;

@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
SysMonitor sysMonitor = new SysMonitor();
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
String osName = osmxb.getName();
//總實體記憶體
long totalPhysicalMemorySize = osmxb.getTotalPhysicalMemorySize()/ 1024L;
//空閒記憶體
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize()/ 1024L;
//已用記憶體
long usedPhysicalMemorySize = totalPhysicalMemorySize - freePhysicalMemorySize;
//記憶體使用率
Double ncsyl = Double.valueOf(usedPhysicalMemorySize)/Double.valueOf(totalPhysicalMemorySize);

//當前cpu系統佔用率
Double cpuzyl = osmxb.getSystemCpuLoad();
sysMonitor.setXtznc(Double.valueOf(totalPhysicalMemorySize));
sysMonitor.setXtsync(Double.valueOf(freePhysicalMemorySize));
//以百分比形式存入
sysMonitor.setNcsyl(ncsyl*100);
sysMonitor.setCpusyl(cpuzyl*100);
sysMonitor.setCjsj(new Date());
//將監控資料入庫
sysMonitorService.save(sysMonitor);
//判斷資料是否異常(目前CPU閾值寫死為80%,記憶體佔比閾值寫死為80%)
if(cpuzyl.compareTo(CPUSYLYZ)>=0){
SysWarning sysWarning = new SysWarning();
sysWarning.setCjsj(new Date());
sysWarning.setClzt(SysWarningDealStatusEnum.NOT_DEAL.getCode());
sysWarning.setGjjb(SysWarningLevelEnum.YYS.getCode());
sysWarning.setGjlx(SysWarningTypeEnum.CPULYLGJ.getCode());
sysWarning.setGjnr(SysWarningTypeEnum.CPULYLGJ.getType());
sysWarning.setGjy(SysWarningSourceEnum.SYSTEM.getCode());
sysWarning.setGjz(cpuzyl*100);
sysWarning.setGjyz(CPUSYLYZ*100);
sysWarningService.save(sysWarning);
}
if(ncsyl.compareTo(NCSYLYZ)>=0){
SysWarning sysWarning = new SysWarning();
sysWarning.setCjsj(new Date());
sysWarning.setClzt(SysWarningDealStatusEnum.NOT_DEAL.getCode());
sysWarning.setGjjb(SysWarningLevelEnum.YYS.getCode());
sysWarning.setGjlx(SysWarningTypeEnum.NCGJ.getCode());
sysWarning.setGjnr(SysWarningTypeEnum.NCGJ.getType());
sysWarning.setGjy(SysWarningSourceEnum.SYSTEM.getCode());
sysWarning.setGjz(ncsyl*100);
sysWarning.setGjyz(NCSYLYZ*100);
sysWarningService.save(sysWarning);
}
}
}
  • 新增新增定時任務方法
public void addJob(String clazzName, String jobName, String groupName, String cronExp, String desc, Map<String, Object> param) {
try {
// 啟動排程器,預設初始化的時候已經啟動
// scheduler.start();
// 獲取jobClass
Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(clazzName);
//獲得JobDataMap,寫入資料
JobDataMap jobDataMap = new JobDataMap();
if (null != param) {
jobDataMap.putAll(param);
}
//構建job資訊
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, groupName).withDescription(desc).setJobData(jobDataMap).build();
//表示式排程構建器(即任務執行的時間)
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExp);
//按新的cronExpression表示式構建一個新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName).withSchedule(scheduleBuilder).usingJobData(jobDataMap).build();

scheduler.scheduleJob(jobDetail, trigger);
} catch (Exception e) {
log.error("建立任務失敗", e);
}
}
  • 查詢所有定時任務
public List<JobInfoDTO> getAllJobs() {
List<JobInfoDTO> jobList = new ArrayList<>();
try {
GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
for (JobKey jobKey : jobKeys) {
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
JobDetail job = scheduler.getJobDetail(jobKey);
for (Trigger trigger : triggers) {
JobInfoDTO jobInfo = buildJobInfo(jobKey, trigger.getKey());
jobInfo.setJobDescription(job.getDescription());
jobInfo.setJobClassName(job.getJobClass().getName());
jobInfo.setJobDataMap(job.getJobDataMap());

setTriggerRule(jobInfo, trigger);
jobList.add(jobInfo);
}
}
} catch (SchedulerException e) {
log.error("QuartzManager getAllJobs is error !!!", e);
throw new RuntimeException(e);
}
return jobList;
}