
通過實作job類可以手動執行自定義的定時任務
實作方式如下:
1、引入jar包:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.3</version>
</dependency>
2、在配置檔案中添加配置
<task:annotation-driven/>
3、建立資料庫
4、定時任務實體類:
package com.aisino.zhgl.plan.model;
import java.util.Date;
import java.io.Serializable;
import com.aisino.zhgl.core.model.BaseModel;
/**
* 定時任務(SysSchedule)實體類
*
* @author
* @since
*/
public class SysSchedule extends BaseModel {
private static final long serialVersionUID = -31279662158620438L;
/**
* id
*/
private String id;
/**
* 任務名
*/
private String name;
/**
* 任務組
*/
private String tGroup;
/**
* 定時規則
*/
private String expression;
/**
* 啟用狀态
*/
private String status;
/**
* 通知使用者
*/
private String isInfo;
/**
* 任務類
*/
private String classname;
/**
* 描述
*/
private String description;
/**
* 建立者
*/
private String createBy;
/**
* 建立時間
*/
private Date createDate;
/**
* 更新者
*/
private String updateBy;
/**
* 更新時間
*/
private Date updateDate;
/**
* 邏輯删除标記(0:顯示;1:隐藏)
*/
private String delFlag;
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTGroup() {
return tGroup;
}
public void setTGroup(String tGroup) {
this.tGroup = tGroup;
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getIsInfo() {
return isInfo;
}
public void setIsInfo(String isInfo) {
this.isInfo = isInfo;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
}
5、定時任務工具類----封裝了調用方法
package com.aisino.zhgl.plan.controller.task;
import com.aisino.zhgl.plan.model.SysSchedule;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Controller;
@Controller
public class QuartzTool {
private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
/**
* 新增一個時間排程器
* @param triggerName
* @param triggerGroupName
* @param jobClass
* @param cron
* @return
*/
public Boolean addQuartz(String triggerName, String triggerGroupName, Class jobClass , String cron){
try {
// 建立一個JobDetail執行個體
JobDetail jobDetail = JobBuilder.newJob(jobClass).build();
// 建立一個CronTrigger,規定Job每隔一秒執行一次
CronTrigger trigger = TriggerBuilder.newTrigger()
// 指定Trigger名稱群組名稱
.startNow().withIdentity(triggerName, triggerGroupName)
// 設定cron運作規則,定義每秒執行一次
.withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
// 得到Scheduler排程器執行個體
Scheduler scheduler = null;
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.scheduleJob(jobDetail, trigger); // 綁定JobDetail和Trigger
scheduler.start(); // 開始任務排程
return true;
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
/**
* 修改一個時間排程器
* @param triggerName
* @param triggerGroupName
* @param cron
* @return
*/
public Boolean modifyQuartz(String triggerName, String triggerGroupName, String cron) {
try {
Scheduler scheduler = schedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
if (trigger == null) {
return false ;
}
String oldTime = trigger.getCronExpression();
if (!oldTime.equalsIgnoreCase(cron)) {
// 觸發器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 觸發器名,觸發器組
triggerBuilder.withIdentity(triggerName, triggerGroupName);
triggerBuilder.startNow();
// 觸發器時間設定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
// 建立Trigger對象
trigger = (CronTrigger) triggerBuilder.build();
// 修改一個任務的觸發時間
scheduler.rescheduleJob(triggerKey, trigger);
}
return true ;
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
/**
* 移除一個定時器
* @param triggerName
* @param triggerGroupName
*/
public Boolean removeQuartz(String triggerName, String triggerGroupName) {
try {
Scheduler scheduler = schedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);
// 停止觸發器
scheduler.pauseTrigger(triggerKey);
// 移除觸發器
scheduler.unscheduleJob(triggerKey);
return true;
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
/**
* 恢複任務
*/
public void restartJob(SysSchedule quartzRequest){
try {
Scheduler scheduler = schedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(quartzRequest.getName(),quartzRequest.getTGroup());
// scheduler.resumeTrigger(triggerKey);
// 停止觸發器
scheduler.pauseTrigger(triggerKey);
// 移除觸發器
scheduler.unscheduleJob(triggerKey);
addQuartz(quartzRequest.getName(),quartzRequest.getTGroup(),Class.forName(quartzRequest.getClassname()),quartzRequest.getExpression());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 立馬執行一次任務
* @param triggerName 任務名
* @param triggerGroupName 任務組
*/
public void startNowJob(String triggerName, String triggerGroupName){
try {
Scheduler scheduler = schedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);
Trigger trigger = scheduler.getTrigger(triggerKey);
JobKey jobKey = trigger.getJobKey();
scheduler.triggerJob(jobKey);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
/**
* 暫停任務
* @param triggerName 任務名
* @param triggerGroupName 任務組
*/
public void stopJob(String triggerName, String triggerGroupName){
try {
Scheduler scheduler = schedulerFactory.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);
// 停止觸發器
scheduler.pauseTrigger(triggerKey);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
/**
*
* 啟動所有定時任務
*/
public Boolean startJobs() {
try {
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.start();
return true;
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
/**
* 功能:關閉所有定時任務
*/
public Boolean shutdownJobs() {
try {
Scheduler scheduler = schedulerFactory.getScheduler();
if (!scheduler.isShutdown()) {
scheduler.shutdown();
}
return true;
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
}
6、定義類實作Job
package com.aisino.zhgl.plan.controller.task;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.text.SimpleDateFormat;
public abstract class Task implements Job {
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
run();
}
public abstract void run();
}
package com.aisino.zhgl.plan.controller.task;
import java.text.SimpleDateFormat;
import java.util.Date;
public class QuartzJob extends Task {
@Override
public void run() {
// 任務邏輯代碼
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設定日期格式
System.out.println("=========================================");
System.out.println("定時任務測試======QuartzJob" + df.format(new Date()));
System.out.println("=========================================");
System.out.println();
}
}
以上可以實作手動添加自定義定時任務的基本功能,具體需要根據業務修改