boot-admin整合Quartz實現動態管理定時任務

2023-04-27 06:00:41

淄博燒烤爆紅出了圈,當你坐在八大局的燒烤攤,面前是火爐、烤串、小餅和蘸料,音樂響起,啤酒倒滿,燒烤靈魂的party即將開場的時候,你係統中的Scheduler(偵錯程式),也自動根據設定的Trigger(觸發器),從容優雅的啟動了一系列的Job(後臺定時任務)。工作一切早有安排,又何須費心勞神呢?因為boot-admin早已將Quartz這塊肉串在了烤簽上!
專案原始碼倉庫github
專案原始碼倉庫gitee

Quartz是一款Java編寫的開源任務排程框架,同時它也是Spring預設的任務排程框架。它的作用其實類似於Timer定時器以及ScheduledExecutorService排程執行緒池,當然Quartz作為一個獨立的任務排程框架表現更為出色,功能更強大,能夠定義更為複雜的執行規則。
boot-admin 是一款採用前後端分離模式、基於 SpringCloud 微服務架構 + vue-element-admin 的 SaaS 後臺管理框架。
那麼boot-admin怎樣才能將Quartz串成串呢?一共分三步:

加入依賴

<dependency>
  <groupId>org.quartz-scheduler</groupId>
  <artifactId>quartz</artifactId>
  <version>2.3.2</version>
</dependency>

前端整合

vue頁面以el-table作為任務的展示控制元件,串起任務的建立、修改、刪除、掛起、恢復、狀態檢視等功能。

vue頁面

<template>
  <div class="app-container" style="background-color: #FFFFFF;">
    <!--功能按鈕區-->
    <div class="cl pd-5 bg-1 bk-gray">
      <div align="left" style="float:left">
        <el-button size="mini" type="primary" @click="search()">查詢</el-button>
        <el-button size="mini" type="primary" @click="handleadd()">新增</el-button>
      </div>
      <div align="right">
        <!--分頁控制元件-->
        <div style="align:right">
          <el-pagination
            :current-page="BaseTableData.page.currentPage"
            :page-sizes="[5,10,20,50,100,500]"
            :page-size="BaseTableData.page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="BaseTableData.page.total"
            @size-change="handlePageSizeChange"
            @current-change="handlePageCurrentChange"
          />
        </div>
        <!--分頁控制元件-->
      </div>
    </div>
    <!--功能按鈕區-->
    <!--表格-->
    <el-table max-height="100%" :data="BaseTableData.table" style="width: 100%" :border="true">
      <el-table-column type="index" :index="indexMethod" />
      <el-table-column prop="jobName" label="任務名稱" width="100px" />
      <el-table-column prop="jobGroup" label="任務所在組" width="100px" />
      <el-table-column prop="jobClassName" label="任務類名" />
      <el-table-column prop="cronExpression" label="表示式" width="120" />
      <el-table-column prop="timeZoneId" label="時區" width="120" />
      <el-table-column prop="startTime" label="開始" width="120" :formatter="(row,column,cellValue) => dateTimeColFormatter(row,column,cellValue)"/>
      <el-table-column prop="nextFireTime" label="下次" width="120" :formatter="(row,column,cellValue) => dateTimeColFormatter(row,column,cellValue)"/>
      <el-table-column prop="previousFireTime" label="上次" width="120" :formatter="(row,column,cellValue) => dateTimeColFormatter(row,column,cellValue)"/>
      <el-table-column prop="triggerState" label="狀態" width="80">
        <template slot-scope="scope">
          <p v-if="scope.row.triggerState=='NORMAL'">等待</p>
          <p v-if="scope.row.triggerState=='PAUSED'">暫停</p>
          <p v-if="scope.row.triggerState=='NONE'">刪除</p>
          <p v-if="scope.row.triggerState=='COMPLETE'">結束</p>
          <p v-if="scope.row.triggerState=='ERROR'">錯誤</p>
          <p v-if="scope.row.triggerState=='BLOCKED'">阻塞</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220px">
        <template slot-scope="scope">
          <el-button type="warning" size="least" title="掛起" @click="handlePause(scope.row)">掛起</el-button>
          <el-button type="primary" size="least" title="恢復" @click="handleResume(scope.row)">恢復</el-button>
          <el-button type="danger" size="least" title="刪除" @click="handleDelete(scope.row)">刪除</el-button>
          <el-button type="success" size="least" title="修改" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--表格-->
    <!--主表單彈出視窗-->
    <el-dialog
      v-cloak
      title="維護"
      :visible.sync="InputBaseInfoDialogData.dialogVisible"
      :close-on-click-modal="InputBaseInfoDialogData.showCloseButton"
      top="5vh"
      :show-close="InputBaseInfoDialogData.showCloseButton"
      :fullscreen="InputBaseInfoDialogData.dialogFullScreen"
    >
      <!--彈窗頭部header-->
      <div slot="title" style="margin-bottom: 10px">
        <div align="left" style="float:left">
          <h3>定時任務管理</h3>
        </div>
        <div align="right">
          <el-button type="text" title="全螢幕顯示" @click="resizeInputBaseInfoDialogMax()"><i class="el-icon-arrow-up" /></el-button>
          <el-button type="text" title="以彈出視窗形式顯示" @click="resizeInputBaseInfoDialogNormal()"><i class="el-icon-arrow-down" /></el-button>
          <el-button type="text" title="關閉" @click="closeInputBaseInfoDialog()"><i class="el-icon-error" /></el-button>
        </div>
      </div>
      <!--彈窗頭部header-->
      <!--彈窗表單-->
      <el-form
        ref="InputBaseInfoForm"
        :status-icon="InputBaseInfoDialogData.statusIcon"
        :model="InputBaseInfoDialogData.data"
        class="demo-ruleForm"
      >
        <el-form-item label="原任務名稱" :label-width="InputBaseInfoDialogData.formLabelWidth" prop="jobName">
          {{ InputBaseInfoDialogData.data.oldJobName }}【修改任務時使用】
        </el-form-item>
        <el-form-item label="原任務分組" :label-width="InputBaseInfoDialogData.formLabelWidth" prop="jobGroup">
          {{ InputBaseInfoDialogData.data.oldJobGroup }}【修改任務時使用】
        </el-form-item>
        <el-form-item label="任務名稱" :label-width="InputBaseInfoDialogData.formLabelWidth" prop="jobName">
          <el-input v-model="InputBaseInfoDialogData.data.jobName" auto-complete="off" />
        </el-form-item>
        <el-form-item label="任務分組" :label-width="InputBaseInfoDialogData.formLabelWidth" prop="jobGroup">
          <el-input v-model="InputBaseInfoDialogData.data.jobGroup" auto-complete="off" />
        </el-form-item>
        <el-form-item label="類名" :label-width="InputBaseInfoDialogData.formLabelWidth" prop="jobClassName">
          <el-input v-model="InputBaseInfoDialogData.data.jobClassName" auto-complete="off" />
        </el-form-item>
        <el-form-item label="表示式" :label-width="InputBaseInfoDialogData.formLabelWidth" prop="cronExpression">
          <el-input v-model="InputBaseInfoDialogData.data.cronExpression" auto-complete="off" />
        </el-form-item>
      </el-form>
      <!--彈窗表單-->
      <!--彈窗尾部footer-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveInputBaseInfoForm()">保 存</el-button>
      </div>
      <!--彈窗尾部footer-->
    </el-dialog>
    <!--彈出視窗-->
    <!--檢視場所彈出視窗-->
    <el-dialog
      v-cloak
      title="修改任務"
      :visible.sync="ViewBaseInfoDialogData.dialogVisible"
      :close-on-click-modal="ViewBaseInfoDialogData.showCloseButton"
      top="5vh"
      :show-close="ViewBaseInfoDialogData.showCloseButton"
      :fullscreen="ViewBaseInfoDialogData.dialogFullScreen"
    >
      <!--彈窗頭部header-->
      <div slot="title" style="margin-bottom: 10px">
        <div align="left" style="float:left">
          <h3>修改任務</h3>
        </div>
        <div align="right">
          <el-button type="text" @click="dialogResize('ViewBaseInfoDialog',true)"><i class="el-icon-arrow-up" title="全螢幕顯示" /></el-button>
          <el-button type="text" @click="dialogResize('ViewBaseInfoDialog',false)"><i
            class="el-icon-arrow-down"
            title="以彈出視窗形式顯示"
          /></el-button>
          <el-button type="text" @click="dialogClose('ViewBaseInfoDialog')"><i class="el-icon-error" title="關閉" /></el-button>
        </div>
      </div>
      <!--彈窗頭部header-->
      <!--彈窗表單-->
      <el-form
        ref="ViewBaseInfoForm"
        :status-icon="ViewBaseInfoDialogData.statusIcon"
        :model="ViewBaseInfoDialogData.data"
        class="demo-ruleForm"
      >
        <el-form-item label="表示式" :label-width="ViewBaseInfoDialogData.formLabelWidth" prop="cronExpression">
          {{ this.BaseTableData.currentRow.cronExpression }}
        </el-form-item>
      </el-form>
      <!--彈窗表單-->
    </el-dialog>
  </div>
</template>
<script>
import {
  getBlankJob,
  fetchJobPage,
  getUpdateObject,
  saveJob,
  pauseJob,
  resumeJob,
  deleteJob
} from '@/api/job'

export default {
  name: 'Jobmanage',
  data: function() {
    return {
      /**
         * 後臺服務忙,防止重複提交的控制變數
         * */
      ServiceRunning: false,
      /**
         *表格和分頁元件
         * */
      BaseTableData: {
        currentRow: {},
        page: {
          currentPage: 1,
          pageSize: 20,
          pageNum: 1,
          pages: 1,
          size: 5,
          total: 1
        },
        /**
           *主表格資料
           * */
        table: [],
        /**
           *勾選選中的資料
           * */
        selected: []
      },
      InputBaseInfoDialogData: {
        data: {},
        dialogVisible: false,
        dialogFullScreen: false,
        formLabelWidth: '180px',
        showCloseButton: false,
        statusIcon: true
      },
      ViewBaseInfoDialogData: {
        cronExpression: '',
        dialogVisible: false,
        dialogFullScreen: true,
        formLabelWidth: '180px'
      }
    }
  },
  /**
     *初始化自動執行查詢表格資料--不用調整
     **/
  mounted: function() {
    this.loadTableData()
  },
  methods: {
    /**
       * 查詢---------根據實際調整引數
       */
    async loadTableData() {
      if (this.ServiceRunning) {
        this.$message({
          message: '請不要重複點選。',
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = true
      const response = await fetchJobPage(this.BaseTableData.page)
      if (response.code !== 100) {
        this.ServiceRunning = false
        this.$message({
          message: response.message,
          type: 'warning'
        })
        return
      }
      const {
        data
      } = response
      this.BaseTableData.page.total = data.total
      this.BaseTableData.table = data.records
      this.ServiceRunning = false
    },
    /**
       * 每頁大小調整事件
       * @param val
       */
    handlePageSizeChange(val) {
      if (val != this.BaseTableData.page.pageSize) {
        this.BaseTableData.page.pageSize = val
        this.loadTableData()
      }
    },
    /**
       * 當前面號調整事件
       * @param val
       */
    handlePageCurrentChange(val) {
      if (val != this.BaseTableData.page.currentPage) {
        this.BaseTableData.page.currentPage = val
        this.loadTableData()
      }
    },
    dialogResize(dialogName, toMax) {
      VFC_dialogResize(dialogName, toMax)
    },
    resizeInputBaseInfoDialogMax() {
      this.InputBaseInfoDialogData.dialogFullScreen = true
    },
    resizeInputBaseInfoDialogNormal() {
      this.InputBaseInfoDialogData.dialogFullScreen = false
    },
    dialogClose(dialogName) {
    },
    closeInputBaseInfoDialog() {
      this.InputBaseInfoDialogData.dialogVisible = false
      this.loadTableData()
    },
    async getBlankForm() {
      const response = await getBlankJob()
      if (response.code !== 100) {
        this.ServiceRunning = false
        this.$message({
          message: response.message,
          type: 'warning'
        })
        return
      }
      const {
        data
      } = response

      this.InputBaseInfoDialogData.data = data
    },
    async getUpdateForm(row) {
      const response = await getUpdateObject(row)
      if (response.code !== 100) {
        this.ServiceRunning = false
        this.$message({
          message: response.message,
          type: 'warning'
        })
        return
      }
      const {
        data
      } = response

      this.InputBaseInfoDialogData.data = data
    },
    // 彈出對話方塊
    handleadd() {
      this.getBlankForm()
      this.InputBaseInfoDialogData.dialogVisible = true
    },
    handleUpdate(row) {
      if (row.triggerState !== 'PAUSED') {
        this.$message({
          message: '請先掛起任務,再修改。',
          type: 'warning'
        })
        return
      }
      this.getUpdateForm(row)
      this.InputBaseInfoDialogData.dialogVisible = true
    },
    search() {
      this.loadTableData()
    },
    /**
       * 提交修改主表單
       */
    async saveInputBaseInfoForm() {
      if (this.ServiceRunning) {
        this.$message({
          message: '請不要重複點選。',
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = true
      const response = await saveJob(this.InputBaseInfoDialogData.data)
      if (response.code !== 100) {
        this.ServiceRunning = false
        this.$message({
          message: response.message,
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = false
      this.$message({
        message: '資料儲存成功。',
        type: 'success'
      })
      this.loadTableData()
    },
    async handlePause(row) {
      if (this.ServiceRunning) {
        this.$message({
          message: '請不要重複點選。',
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = true
      const response = await pauseJob(row)
      if (response.code !== 100) {
        this.ServiceRunning = false
        this.$message({
          message: response.message,
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = false
      this.$message({
        message: '任務成功掛起。',
        type: 'success'
      })
      this.loadTableData()
    },
    async handleResume(row) {
      if (this.ServiceRunning) {
        this.$message({
          message: '請不要重複點選。',
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = true
      const response = await resumeJob(row)
      if (response.code !== 100) {
        this.ServiceRunning = false
        this.$message({
          message: response.message,
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = false
      this.$message({
        message: '任務成功恢復。',
        type: 'success'
      })
      this.loadTableData()
    },
    async handleDelete(row) {
      if (row.triggerState !== 'PAUSED') {
        this.$message({
          message: '請先掛起任務,再刪除。',
          type: 'warning'
        })
        return
      }
      if (this.ServiceRunning) {
        this.$message({
          message: '請不要重複點選。',
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = true
      const response = await deleteJob(row)
      if (response.code !== 100) {
        this.ServiceRunning = false
        this.$message({
          message: response.message,
          type: 'warning'
        })
        return
      }
      this.ServiceRunning = false
      this.$message({
        message: '任務成功刪除。',
        type: 'success'
      })
      this.loadTableData()
    },
    indexMethod(index) {
      return this.BaseTableData.page.pageSize * (this.BaseTableData.page.currentPage - 1) + index + 1
    },
    dateTimeColFormatter(row, column, cellValue) {
      return this.$commonUtils.dateTimeFormat(cellValue)
    },
  }
}
</script>
<style>
</style>

api定義

job.js定義存取後臺介面的方式

import request from '@/utils/request'
//獲取空任務
export function getBlankJob() {
  return request({
    url: '/api/system/auth/job/blank',
    method: 'get'
  })
}
//獲取任務列表(分頁)
export function fetchJobPage(data) {
  return request({
    url: '/api/system/auth/job/page',
    method: 'post',
    data
  })
}
//獲取用於修改的任務資訊
export function getUpdateObject(data) {
  return request({
    url: '/api/system/auth/job/dataforupdate',
    method: 'post',
    data
  })
}
//儲存任務
export function saveJob(data) {
  return request({
    url: '/api/system/auth/job/save',
    method: 'post',
    data
  })
}
//暫停任務
export function pauseJob(data) {
  return request({
    url: '/api/system/auth/job/pause',
    method: 'post',
    data
  })
}
//恢復任務
export function resumeJob(data) {
  return request({
    url: '/api/system/auth/job/resume',
    method: 'post',
    data
  })
}
//刪除任務
export function deleteJob(data) {
  return request({
    url: '/api/system/auth/job/delete',
    method: 'post',
    data
  })
}

後端整合

設定類

單獨資料來源設定

Quartz會自動建立11張資料表,資料來源可以與系統主資料來源相同,也可以獨立設定。

筆者建議單獨設定Quartz資料來源。在組態檔 application.yml 新增以下內容

base2048:
  job:
    enable: true
    datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/base2048job?useSSL=false&serverTimezone=UTC&autoReconnect=true&allowPublicKeyRetrieval=true&useOldAliasMetadataBehavior=true
      username: root
      password: mysql

資料來源設定類如下:

@Configuration
public class QuartzDataSourceConfig {
    @Primary
    @Bean(name = "defaultDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }
    @Bean(name = "quartzDataSource")
    @QuartzDataSource
    @ConfigurationProperties(prefix = "base2048.job.datasource")
    public DruidDataSource quartzDataSource() {
        return new DruidDataSource();
    }
}

排程器設定

在 resources 下新增 quartz.properties 檔案,內容如下:

# 固定字首org.quartz
# 主要分為scheduler、threadPool、jobStore、plugin等部分
#
#
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false

<!-- 每個叢集節點要有獨立的instanceId -->
org.quartz.scheduler.instanceId = 'AUTO'
# 範例化ThreadPool時,使用的執行緒類為SimpleThreadPool
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
# threadCount和threadPriority將以setter的形式注入ThreadPool範例
# 並行個數
org.quartz.threadPool.threadCount = 15
# 優先順序
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
org.quartz.jobStore.misfireThreshold = 5000

# 預設儲存在記憶體中
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
#持久化
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.dataSource = qzDS
org.quartz.dataSource.qzDS.maxConnections = 10

排程器設定類內容如下:

@Configuration
public class SchedulerConfig {
    @Autowired
    private MyJobFactory myJobFactory;
    @Value("${base2048.job.enable:false}")
    private Boolean JOB_LOCAL_RUNING;
    @Value("${base2048.job.datasource.driver-class-name}")
    private String dsDriver;
    @Value("${base2048.job.datasource.url}")
    private String dsUrl;
    @Value("${base2048.job.datasource.username}")
    private String dsUser;
    @Value("${base2048.job.datasource.password}")
    private String dsPassword;
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setOverwriteExistingJobs(true);
        // 延時啟動
        factory.setStartupDelay(20);
        // 用於quartz叢集,QuartzScheduler 啟動時更新己存在的Job
        // factory.setOverwriteExistingJobs(true);
        // 載入quartz資料來源設定
        factory.setQuartzProperties(quartzProperties());
        // 自定義Job Factory,用於Spring注入
        factory.setJobFactory(myJobFactory);
        // 在com.neusoft.jn.gpbase.quartz.job.BaseJobTemplate 同樣出現該設定
        //原因 : qrtz 在叢集模式下 存在 同一個任務 一個在A伺服器任務被分配出去 另一個B伺服器任務不再分配的情況.
        //
        if(!JOB_LOCAL_RUNING){
            // 設定排程器自動執行
            factory.setAutoStartup(false);
        }
        return factory;
    }
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        Properties properties = propertiesFactoryBean.getObject();
        properties.setProperty("org.quartz.dataSource.qzDS.driver",dsDriver);
        properties.setProperty("org.quartz.dataSource.qzDS.URL",dsUrl);
        properties.setProperty("org.quartz.dataSource.qzDS.user",dsUser);
        properties.setProperty("org.quartz.dataSource.qzDS.password",dsPassword);
        return properties;
    }

    /*
     * 通過SchedulerFactoryBean獲取Scheduler的範例
     */
    @Bean(name="scheduler")
    public Scheduler scheduler() throws Exception {
        return schedulerFactoryBean().getScheduler();
    }
}

任務模板

Job基礎類別

public abstract class BaseJob implements Job, Serializable {
    private static final String JOB_MAP_KEY = "self";
    public static final String STATUS_RUNNING = "1";
    public static final String STATUS_NOT_RUNNING = "0";
    public static final String CONCURRENT_IS = "1";
    public static final String CONCURRENT_NOT = "0";
    /**
     * 任務名稱
     */
    private String jobName;
    /**
     * 任務分組
     */
    private String jobGroup;
    /**
     * 任務狀態 是否啟動任務
     */
    private String jobStatus;
    /**
     * cron表示式
     */
    private String cronExpression;
    /**
     * 描述
     */
    private String description;
    /**
     * 任務執行時呼叫哪個類的方法 包名+類名
     */
    private Class beanClass = this.getClass();
    /**
     * 任務是否有狀態
     */
    private String isConcurrent;
    /**
     * Spring bean
     */
    private String springBean;
    /**
     * 任務呼叫的方法名
     */
    private String methodName;
    /**
     * 為了將執行後的任務持久化到資料庫中
     */
    @JsonIgnore
    private JobDataMap dataMap = new JobDataMap();

    public JobKey getJobKey(){
        return JobKey.jobKey(jobName, jobGroup);// 任務名稱和組構成任務key
    }
    public JobDataMap getDataMap(){
        if(dataMap.size() == 0){
            dataMap.put(JOB_MAP_KEY,this);
        }
        return dataMap;
    }
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    public String getJobGroup() {
        return jobGroup;
    }
    public void setJobGroup(String jobGroup) {
        this.jobGroup = jobGroup;
    }
    public String getJobStatus() {
        return jobStatus;
    }
    public void setJobStatus(String jobStatus) {
        this.jobStatus = jobStatus;
    }
    public String getCronExpression() {
        return cronExpression;
    }
    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Class getBeanClass() {
        return beanClass;
    }
    public void setBeanClass(Class beanClass) {
        this.beanClass = beanClass;
    }
    public String getIsConcurrent() {
        return isConcurrent;
    }
    public void setIsConcurrent(String isConcurrent) {
        this.isConcurrent = isConcurrent;
    }
    public String getSpringBean() {
        return springBean;
    }
    public void setSpringBean(String springBean) {
        this.springBean = springBean;
    }
    public String getMethodName() {
        return methodName;
    }
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
}

Job模板類

@Slf4j
public abstract class BaseJobTemplate extends BaseJob {
    @Value("${base2048.job.enable:false}")
    private Boolean JOB_LOCAL_RUNING;
    @Override
    public final void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        if (JOB_LOCAL_RUNING) {
            try {
                this.runing(jobExecutionContext);
            } catch (Exception ex) {
                throw new JobExecutionException(ex);
            }
        } else {
            log.info("設定引數不允許在本機執行定時任務");
        }
    }
    public abstract void runing(JobExecutionContext jobExecutionContext);
}

Job範例類

業務Job從模板類繼承。

@Slf4j
@Component
@DisallowConcurrentExecution
public class TestJob extends BaseJobTemplate {
    @Override
    public void runing(JobExecutionContext jobExecutionContext)  {
        try {
            log.info("測試任務開始:【{}】", Instant.now().atOffset(ZoneOffset.ofHours(8)));
            System.out.println("============= 測試任務正在執行 =====================");
            System.out.println("============= Test job is running ===============");
            log.info("測試任務結束:【{}】", Instant.now().atOffset(ZoneOffset.ofHours(8)));
        } catch (Exception ex) {
            log.error("測試任務異常:【{}】", Instant.now().atOffset(ZoneOffset.ofHours(8)));
            log.error(ex.getMessage(), ex);
        }
    }
}

管理功能

Controller

@RestController
@RequestMapping("/api/system/auth/job")
@Slf4j
public class QuartzJobController {
    @Resource
    private QuartzService quartzService;

    @PostMapping("/save")
    @ApiOperation(value = "儲存新增或修改任務",notes = "儲存新增或修改任務")
    public ResultDTO addOrUpdate(@RequestBody JobUpdateDTO jobUpdateDTO) throws Exception {
        if (StringUtils.isBlank(jobUpdateDTO.getOldJobName())) {
            ResultDTO resultDTO = this.addSave(jobUpdateDTO);
            return resultDTO;
        } else {
            /**
             * 先刪除後新增
             */
            JobDTO jobDTO = new JobDTO();
            jobDTO.setJobName(jobUpdateDTO.getOldJobName());
            jobDTO.setJobGroup(jobUpdateDTO.getOldJobGroup());
            this.delete(jobDTO);
            ResultDTO resultDTO = this.addSave(jobUpdateDTO);
            return resultDTO;
        }
    }
    private ResultDTO addSave(@RequestBody JobUpdateDTO jobUpdateDTO) throws Exception {
        BaseJob job = (BaseJob) Class.forName(jobUpdateDTO.getJobClassName()).newInstance();
        job.setJobName(jobUpdateDTO.getJobName());
        job.setJobGroup(jobUpdateDTO.getJobGroup());
        job.setDescription(jobUpdateDTO.getDescription());
        job.setCronExpression(jobUpdateDTO.getCronExpression());
        try {
            quartzService.addJob(job);
            return  ResultDTO.success();
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            return ResultDTO.failureCustom("儲存新增任務時服務發生意外情況。");
        }
    }
    @PostMapping("/page")
    @ApiOperation(value = "查詢任務",notes = "查詢任務")
    public ResultDTO getJobPage(@RequestBody BasePageQueryVO basePageQueryVO) {
        try {
            IPage<JobDTO> jobDtoPage = quartzService.queryJob(basePageQueryVO.getCurrentPage(),basePageQueryVO.getPageSize());
            return  ResultDTO.success(jobDtoPage);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            return ResultDTO.failureCustom("查詢任務時服務發生意外情況。");
        }
    }
    @PostMapping("/pause")
    @ApiOperation(value = "暫停任務",notes = "暫停任務")
    public ResultDTO pause(@RequestBody JobDTO jobDTO) {
        try {
            quartzService.pauseJob(jobDTO.getJobName(),jobDTO.getJobGroup());
            return ResultDTO.success();
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            return ResultDTO.failureCustom("暫停任務時服務發生意外情況。");
        }
    }

    @PostMapping("/resume")
    @ApiOperation(value = "恢復任務",notes = "恢復任務")
    public ResultDTO resume(@RequestBody JobDTO jobDTO) {
        try {
            quartzService.resumeJob(jobDTO.getJobName(),jobDTO.getJobGroup());
            return ResultDTO.success();
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            return ResultDTO.failureCustom("恢復任務時服務發生意外情況。");
        }
    }
    @PostMapping("/delete")
    @ApiOperation(value = "刪除任務",notes = "刪除任務")
    public ResultDTO delete(@RequestBody JobDTO jobDTO) {
        try {
            if(quartzService.deleteJob(jobDTO.getJobName(),jobDTO.getJobGroup())) {
                return ResultDTO.failureCustom("刪除失敗。");
            }else{
                return ResultDTO.success();
            }
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            return ResultDTO.failureCustom("刪除任務時服務發生意外情況。");
        }
    }
    @GetMapping("/blank")
    public ResultDTO getBlankJobDTO(){
        JobUpdateDTO jobUpdateDTO = new JobUpdateDTO();
        jobUpdateDTO.setJobClassName("com.qiyuan.base2048.quartz.job.jobs.");
        jobUpdateDTO.setCronExpression("*/9 * * * * ?");
        return ResultDTO.success(jobUpdateDTO);
    }
    @PostMapping("/dataforupdate")
    public ResultDTO getUpdateJobDTO(@RequestBody JobDTO jobDTO){
        JobUpdateDTO jobUpdateDTO = JobDtoTransMapper.INSTANCE.map(jobDTO);
        jobUpdateDTO.setOldJobName(jobDTO.getJobName());
        jobUpdateDTO.setOldJobGroup(jobDTO.getJobGroup());
        return ResultDTO.success(jobUpdateDTO);
    }
}

JobDTO

@Data
public class JobDTO {
    private String jobClassName;
    private String jobName;
    private String jobGroup;
    private String description;
    private String cronExpression;
    private String triggerName;
    private String triggerGroup;
    private String timeZoneId;
    private String triggerState;
    private Date startTime;
    private Date nextFireTime;
    private Date previousFireTime;
}

JobUpdateDTO

@Data
public class JobUpdateDTO  extends JobDTO{
    private String oldJobName;
    private String oldJobGroup;
}

Service

@Service
@Slf4j
public class QuartzServiceImpl implements QuartzService {
    /**
     * Scheduler代表一個排程容器,一個排程容器可以註冊多個JobDetail和Trigger.當Trigger和JobDetail組合,就可以被Scheduler容器排程了
     */
    @Autowired
    private Scheduler scheduler;
    @Resource
    private QrtzJobDetailsMapper qrtzJobDetailsMapper;
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    public QuartzServiceImpl(Scheduler scheduler){
        this.scheduler = scheduler;
    }

    @Override
    public IPage<JobDTO> queryJob(int pageNum, int pageSize) throws Exception{
        List<JobDTO> jobList = null;
        try {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            jobList = new ArrayList<>();
            for (JobKey jobKey : jobKeys) {
                List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                for (Trigger trigger : triggers) {
                    JobDTO jobDetails = new JobDTO();
                    if (trigger instanceof CronTrigger) {
                        CronTrigger cronTrigger = (CronTrigger) trigger;
                        jobDetails.setCronExpression(cronTrigger.getCronExpression());
                        jobDetails.setTimeZoneId(cronTrigger.getTimeZone().getDisplayName());
                    }
                    jobDetails.setTriggerGroup(trigger.getKey().getName());
                    jobDetails.setTriggerName(trigger.getKey().getGroup());
                    jobDetails.setJobGroup(jobKey.getGroup());
                    jobDetails.setJobName(jobKey.getName());
                    jobDetails.setStartTime(trigger.getStartTime());
                    jobDetails.setJobClassName(scheduler.getJobDetail(jobKey).getJobClass().getName());
                    jobDetails.setNextFireTime(trigger.getNextFireTime());
                    jobDetails.setPreviousFireTime(trigger.getPreviousFireTime());
                    jobDetails.setTriggerState(scheduler.getTriggerState(trigger.getKey()).name());
                    jobList.add(jobDetails);
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        IPage<JobDTO> jobDTOPage = new Page<>(pageNum,pageSize);
        jobDTOPage.setRecords(jobList);
        jobDTOPage.setTotal(jobList.size());
        jobDTOPage.setCurrent(1);
        jobDTOPage.setPages(1);
        jobDTOPage.setSize(jobList.size());
        return jobDTOPage;
    }

    /**
     * 新增一個任務
     * @param job
     * @throws SchedulerException
     */
    @Override
    public void addJob(BaseJob job) throws SchedulerException {
        /** 建立JobDetail範例,繫結Job實現類
         * JobDetail 表示一個具體的可執行的排程程式,job是這個可執行排程程式所要執行的內容
         * 另外JobDetail還包含了這個任務排程的方案和策略**/
        // 指明job的名稱,所在組的名稱,以及繫結job類
        JobDetail jobDetail = JobBuilder.newJob(job.getBeanClass())
                .withIdentity(job.getJobKey())
                .withDescription(job.getDescription())
                .usingJobData(job.getDataMap())
                .build();
        /**
         * Trigger代表一個排程引數的設定,什麼時候去排程
         */
        //定義排程觸發規則, 使用cronTrigger規則
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(job.getJobName(),job.getJobGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression()))
                .startNow()
                .build();
        //將任務和觸發器註冊到任務排程中去
        scheduler.scheduleJob(jobDetail,trigger);
        //判斷排程器是否啟動
        if(!scheduler.isStarted()){
            scheduler.start();
        }
        log.info(String.format("定時任務:%s.%s-已新增到排程器!", job.getJobGroup(),job.getJobName()));
    }
    /**
     * 根據任務名和任務組名來暫停一個任務
     * @param jobName
     * @param jobGroupName
     * @throws SchedulerException
     */
    @Override
    public void pauseJob(String jobName,String jobGroupName) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(jobName,jobGroupName));
    }
    /**
     * 根據任務名和任務組名來恢復一個任務
     * @param jobName
     * @param jobGroupName
     * @throws SchedulerException
     */
    @Override
    public void resumeJob(String jobName,String jobGroupName) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(jobName,jobGroupName));
    }
    public void rescheduleJob(String jobName,String jobGroupName,String cronExpression,String description) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
        // 表示式排程構建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        // 按新的cronExpression表示式重新構建trigger
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withDescription(description).withSchedule(scheduleBuilder).build();
        // 按新的trigger重新設定job執行
        scheduler.rescheduleJob(triggerKey, trigger);
    }
    /**
     * 根據任務名和任務組名來刪除一個任務
     * @param jobName
     * @param jobGroupName
     * @throws SchedulerException
     */
    @Override
    public boolean deleteJob(String jobName,String jobGroupName) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName,jobGroupName);
        scheduler.pauseTrigger(triggerKey); //先暫停
        scheduler.unscheduleJob(triggerKey); //取消排程
        boolean flag = scheduler.deleteJob(JobKey.jobKey(jobName,jobGroupName)); 
        return flag;
    }
    private JobDTO createJob(String jobName, String jobGroup, Scheduler scheduler, Trigger trigger)
            throws SchedulerException {
        JobDTO job = new JobDTO();
        job.setJobName(jobName);
        job.setJobGroup(jobGroup);
        job.setDescription("觸發器:" + trigger.getKey());
        Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
        job.setTriggerState(triggerState.name());
        if(trigger instanceof CronTrigger) {
            CronTrigger cronTrigger = (CronTrigger)trigger;
            String cronExpression = cronTrigger.getCronExpression();
            job.setCronExpression(cronExpression);
        }
        return job;
    }
}

至此,烤串完畢,火侯正好,外酥裡嫩!

專案原始碼倉庫github
專案原始碼倉庫gitee