|
|
@@ -0,0 +1,346 @@
|
|
|
+package com.storlead.schedule.service;
|
|
|
+
|
|
|
+import com.baomidou.dynamic.datasource.annotation.DS;
|
|
|
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
+import com.baomidou.mybatisplus.core.metadata.IPage;
|
|
|
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
|
|
+import com.storlead.framework.common.constant.DSConstants;
|
|
|
+import com.storlead.framework.common.result.Result;
|
|
|
+import com.storlead.schedule.config.StdScheduleProperties;
|
|
|
+import com.storlead.schedule.constant.StdScheduleConstants;
|
|
|
+import com.storlead.schedule.dto.StdScheduleInstanceQueryDTO;
|
|
|
+import com.storlead.schedule.dto.StdScheduleJobQueryDTO;
|
|
|
+import com.storlead.schedule.dto.StdScheduleJobSaveDTO;
|
|
|
+import com.storlead.schedule.engine.JobHandlerRegistry;
|
|
|
+import com.storlead.schedule.engine.StdScheduleJobCache;
|
|
|
+import com.storlead.schedule.entity.StdScheduleInstanceEntity;
|
|
|
+import com.storlead.schedule.entity.StdScheduleJobEntity;
|
|
|
+import com.storlead.schedule.entity.StdScheduleNodeEntity;
|
|
|
+import com.storlead.schedule.mapper.StdScheduleInstanceMapper;
|
|
|
+import com.storlead.schedule.mapper.StdScheduleJobMapper;
|
|
|
+import com.storlead.schedule.mapper.StdScheduleNodeMapper;
|
|
|
+import com.storlead.schedule.util.CronNextTimeUtils;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.dao.DuplicateKeyException;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.transaction.annotation.Transactional;
|
|
|
+import org.springframework.transaction.support.TransactionSynchronization;
|
|
|
+import org.springframework.transaction.support.TransactionSynchronizationManager;
|
|
|
+import org.springframework.util.CollectionUtils;
|
|
|
+import org.springframework.util.ObjectUtils;
|
|
|
+import org.springframework.util.StringUtils;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.util.Collection;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.Date;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Set;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 调度管理(UI 后端接口实现)。
|
|
|
+ * <p>
|
|
|
+ * 改 cron / 暂停:作废 WAITING、重算 next_fire_time;不打断 RUNNING。
|
|
|
+ * <p>
|
|
|
+ * 改库成功后按 id 从 DB 重载内存缓存(先 DB 再内存;改哪个加载哪个)。
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Service
|
|
|
+@DS(DSConstants.DATASOURCE_MASTER)
|
|
|
+public class StdScheduleJobAdminService {
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private StdScheduleJobMapper stdScheduleJobMapper;
|
|
|
+ @Resource
|
|
|
+ private StdScheduleInstanceMapper stdScheduleInstanceMapper;
|
|
|
+ @Resource
|
|
|
+ private StdScheduleNodeMapper stdScheduleNodeMapper;
|
|
|
+ @Resource
|
|
|
+ private JobHandlerRegistry handlerRegistry;
|
|
|
+ @Resource
|
|
|
+ private StdScheduleProperties properties;
|
|
|
+ @Resource
|
|
|
+ private StdScheduleJobCache jobCache;
|
|
|
+
|
|
|
+ public Result<Object> pageJobs(StdScheduleJobQueryDTO query) {
|
|
|
+ if (query == null) {
|
|
|
+ query = new StdScheduleJobQueryDTO();
|
|
|
+ }
|
|
|
+ Page<StdScheduleJobEntity> page = new Page<>(
|
|
|
+ query.getPageIndex() == null ? 1 : query.getPageIndex(),
|
|
|
+ query.getPageSize() == null ? 10 : query.getPageSize());
|
|
|
+ LambdaQueryWrapper<StdScheduleJobEntity> qw = new LambdaQueryWrapper<>();
|
|
|
+ qw.eq(StdScheduleJobEntity::getIsDelete, 0);
|
|
|
+ if (StringUtils.hasText(query.getJobKey())) {
|
|
|
+ qw.like(StdScheduleJobEntity::getJobKey, query.getJobKey().trim());
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(query.getJobName())) {
|
|
|
+ qw.like(StdScheduleJobEntity::getJobName, query.getJobName().trim());
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(query.getHandler())) {
|
|
|
+ qw.eq(StdScheduleJobEntity::getHandler, query.getHandler().trim());
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(query.getStatus())) {
|
|
|
+ qw.eq(StdScheduleJobEntity::getStatus, query.getStatus().trim());
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(query.getAppGroup())) {
|
|
|
+ qw.eq(StdScheduleJobEntity::getAppGroup, query.getAppGroup().trim());
|
|
|
+ }
|
|
|
+ qw.orderByDesc(StdScheduleJobEntity::getUpdateTime);
|
|
|
+ IPage<StdScheduleJobEntity> result = stdScheduleJobMapper.selectPage(page, qw);
|
|
|
+ return Result.result(result);
|
|
|
+ }
|
|
|
+
|
|
|
+ public Result<Object> getById(Long id) {
|
|
|
+ if (ObjectUtils.isEmpty(id)) {
|
|
|
+ return Result.error("id 不能为空");
|
|
|
+ }
|
|
|
+ StdScheduleJobEntity job = stdScheduleJobMapper.selectById(id);
|
|
|
+ if (job == null || Integer.valueOf(1).equals(job.getIsDelete())) {
|
|
|
+ return Result.error("任务不存在");
|
|
|
+ }
|
|
|
+ return Result.result(job);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Transactional(rollbackFor = Exception.class)
|
|
|
+ public Result<Object> save(StdScheduleJobSaveDTO dto) {
|
|
|
+ if (dto == null) {
|
|
|
+ return Result.error("参数不能为空");
|
|
|
+ }
|
|
|
+ if (!StringUtils.hasText(dto.getJobKey()) || !StringUtils.hasText(dto.getHandler())
|
|
|
+ || !StringUtils.hasText(dto.getCronExpr())) {
|
|
|
+ return Result.error("jobKey / handler / cronExpr 不能为空");
|
|
|
+ }
|
|
|
+ CronNextTimeUtils.validate(dto.getCronExpr());
|
|
|
+ String timezone = StringUtils.hasText(dto.getTimezone()) ? dto.getTimezone().trim() : "Asia/Shanghai";
|
|
|
+ Date next = CronNextTimeUtils.nextFromNow(dto.getCronExpr(), timezone);
|
|
|
+
|
|
|
+ Date now = new Date();
|
|
|
+ if (dto.getId() == null) {
|
|
|
+ StdScheduleJobEntity entity = new StdScheduleJobEntity();
|
|
|
+ fillFromDto(entity, dto, timezone);
|
|
|
+ entity.setStatus(StringUtils.hasText(dto.getStatus()) ? dto.getStatus().trim() : StdScheduleConstants.STATUS_ENABLED);
|
|
|
+ entity.setNextFireTime(next);
|
|
|
+ entity.setCreateTime(now);
|
|
|
+ entity.setUpdateTime(now);
|
|
|
+ entity.setIsDelete(0);
|
|
|
+ try {
|
|
|
+ stdScheduleJobMapper.insert(entity);
|
|
|
+ } catch (DuplicateKeyException e) {
|
|
|
+ return Result.error("jobKey 已存在: " + dto.getJobKey());
|
|
|
+ }
|
|
|
+ reloadCacheAfterCommit(entity.getId());
|
|
|
+ return Result.result(entity);
|
|
|
+ }
|
|
|
+
|
|
|
+ StdScheduleJobEntity existing = stdScheduleJobMapper.selectById(dto.getId());
|
|
|
+ if (existing == null || Integer.valueOf(1).equals(existing.getIsDelete())) {
|
|
|
+ return Result.error("任务不存在");
|
|
|
+ }
|
|
|
+ boolean cronChanged = !dto.getCronExpr().trim().equals(existing.getCronExpr())
|
|
|
+ || !timezone.equals(existing.getTimezone() == null ? "Asia/Shanghai" : existing.getTimezone());
|
|
|
+
|
|
|
+ fillFromDto(existing, dto, timezone);
|
|
|
+ if (StringUtils.hasText(dto.getStatus())) {
|
|
|
+ existing.setStatus(dto.getStatus().trim());
|
|
|
+ }
|
|
|
+ // 改 cron:作废 WAITING + 重算 next;RUNNING 不打断
|
|
|
+ if (cronChanged) {
|
|
|
+ stdScheduleInstanceMapper.deleteWaitingByJobId(existing.getId());
|
|
|
+ existing.setNextFireTime(next);
|
|
|
+ }
|
|
|
+ existing.setUpdateTime(now);
|
|
|
+ stdScheduleJobMapper.updateById(existing);
|
|
|
+ reloadCacheAfterCommit(existing.getId());
|
|
|
+ return Result.result(existing);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void fillFromDto(StdScheduleJobEntity entity, StdScheduleJobSaveDTO dto, String timezone) {
|
|
|
+ entity.setJobKey(dto.getJobKey().trim());
|
|
|
+ entity.setJobName(dto.getJobName());
|
|
|
+ entity.setHandler(dto.getHandler().trim());
|
|
|
+ entity.setCronExpr(dto.getCronExpr().trim());
|
|
|
+ entity.setTimezone(timezone);
|
|
|
+ entity.setConcurrent(dto.getConcurrent() == null ? StdScheduleConstants.CONCURRENT_FORBID : dto.getConcurrent());
|
|
|
+ entity.setAppGroup(StringUtils.hasText(dto.getAppGroup()) ? dto.getAppGroup().trim() : "common");
|
|
|
+ entity.setTimeoutSec(dto.getTimeoutSec() == null ? properties.getDefaultTimeoutSec() : dto.getTimeoutSec());
|
|
|
+ entity.setMisfirePolicy(StdScheduleConstants.MISFIRE_SKIP);
|
|
|
+ entity.setDescription(dto.getDescription());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Transactional(rollbackFor = Exception.class)
|
|
|
+ public Result<Object> pause(Long id) {
|
|
|
+ return updateStatus(id, StdScheduleConstants.STATUS_PAUSED, true);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Transactional(rollbackFor = Exception.class)
|
|
|
+ public Result<Object> enable(Long id) {
|
|
|
+ Result<Object> r = updateStatus(id, StdScheduleConstants.STATUS_ENABLED, false);
|
|
|
+ if (r != null && r.isSuccess()) {
|
|
|
+ StdScheduleJobEntity job = stdScheduleJobMapper.selectById(id);
|
|
|
+ if (job != null && job.getNextFireTime() != null && job.getNextFireTime().before(new Date())) {
|
|
|
+ // 恢复时若 next 已过期,拨到未来下一拍,避免立刻风暴
|
|
|
+ Date next = CronNextTimeUtils.nextFromNow(job.getCronExpr(), job.getTimezone());
|
|
|
+ job.setNextFireTime(next);
|
|
|
+ job.setUpdateTime(new Date());
|
|
|
+ stdScheduleJobMapper.updateById(job);
|
|
|
+ }
|
|
|
+ reloadCacheAfterCommit(id);
|
|
|
+ }
|
|
|
+ return r;
|
|
|
+ }
|
|
|
+
|
|
|
+ private Result<Object> updateStatus(Long id, String status, boolean discardWaiting) {
|
|
|
+ if (ObjectUtils.isEmpty(id)) {
|
|
|
+ return Result.error("id 不能为空");
|
|
|
+ }
|
|
|
+ StdScheduleJobEntity job = stdScheduleJobMapper.selectById(id);
|
|
|
+ if (job == null || Integer.valueOf(1).equals(job.getIsDelete())) {
|
|
|
+ return Result.error("任务不存在");
|
|
|
+ }
|
|
|
+ job.setStatus(status);
|
|
|
+ job.setUpdateTime(new Date());
|
|
|
+ stdScheduleJobMapper.updateById(job);
|
|
|
+ if (discardWaiting) {
|
|
|
+ stdScheduleInstanceMapper.deleteWaitingByJobId(id);
|
|
|
+ }
|
|
|
+ reloadCacheAfterCommit(id);
|
|
|
+ return Result.ok();
|
|
|
+ }
|
|
|
+
|
|
|
+ @Transactional(rollbackFor = Exception.class)
|
|
|
+ public Result<Object> delete(List<Long> ids) {
|
|
|
+ if (CollectionUtils.isEmpty(ids)) {
|
|
|
+ return Result.error("ids 不能为空");
|
|
|
+ }
|
|
|
+ for (Long id : ids) {
|
|
|
+ if (id == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ int running = stdScheduleInstanceMapper.countRunning(id);
|
|
|
+ if (running > 0) {
|
|
|
+ return Result.error("任务 id=" + id + " 仍有 RUNNING 实例,禁止删除");
|
|
|
+ }
|
|
|
+ StdScheduleJobEntity job = stdScheduleJobMapper.selectById(id);
|
|
|
+ if (job == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ job.setIsDelete(1);
|
|
|
+ job.setStatus(StdScheduleConstants.STATUS_PAUSED);
|
|
|
+ job.setUpdateTime(new Date());
|
|
|
+ stdScheduleJobMapper.updateById(job);
|
|
|
+ stdScheduleInstanceMapper.deleteWaitingByJobId(id);
|
|
|
+ }
|
|
|
+ reloadCacheAfterCommit(ids);
|
|
|
+ return Result.ok();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 立即执行:插入一条 MANUAL WAITING,不改 cron 的 next_fire_time。
|
|
|
+ * 禁止并发且已有 RUNNING 时拒绝。
|
|
|
+ */
|
|
|
+ @Transactional(rollbackFor = Exception.class)
|
|
|
+ public Result<Object> triggerNow(Long id) {
|
|
|
+ if (ObjectUtils.isEmpty(id)) {
|
|
|
+ return Result.error("id 不能为空");
|
|
|
+ }
|
|
|
+ StdScheduleJobEntity job = stdScheduleJobMapper.selectById(id);
|
|
|
+ if (job == null || Integer.valueOf(1).equals(job.getIsDelete())) {
|
|
|
+ return Result.error("任务不存在");
|
|
|
+ }
|
|
|
+ if (Integer.valueOf(StdScheduleConstants.CONCURRENT_FORBID).equals(job.getConcurrent())
|
|
|
+ && stdScheduleInstanceMapper.countRunning(id) > 0) {
|
|
|
+ return Result.error("任务禁止并发且当前有 RUNNING,无法立即执行");
|
|
|
+ }
|
|
|
+ Date now = new Date();
|
|
|
+ // fire_time 精确到秒,避免唯一键撞上同一秒的 cron 票:手动用 now+1ms 不够,用秒级偏移
|
|
|
+ Date fireTime = new Date(now.getTime());
|
|
|
+ StdScheduleInstanceEntity inst = new StdScheduleInstanceEntity();
|
|
|
+ inst.setJobId(job.getId());
|
|
|
+ inst.setJobKey(job.getJobKey());
|
|
|
+ inst.setFireTime(fireTime);
|
|
|
+ inst.setTriggerType(StdScheduleConstants.TRIGGER_MANUAL);
|
|
|
+ inst.setStatus(StdScheduleConstants.INST_WAITING);
|
|
|
+ inst.setVersion(0);
|
|
|
+ inst.setCreateTime(now);
|
|
|
+ inst.setUpdateTime(now);
|
|
|
+ try {
|
|
|
+ stdScheduleInstanceMapper.insert(inst);
|
|
|
+ } catch (DuplicateKeyException e) {
|
|
|
+ // 同一秒已有实例:微调 1 秒再试一次
|
|
|
+ fireTime = new Date(now.getTime() + 1000L);
|
|
|
+ inst.setFireTime(fireTime);
|
|
|
+ try {
|
|
|
+ stdScheduleInstanceMapper.insert(inst);
|
|
|
+ } catch (DuplicateKeyException e2) {
|
|
|
+ return Result.error("触发失败:该秒已有执行实例,请稍后重试");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return Result.result(inst);
|
|
|
+ }
|
|
|
+
|
|
|
+ public Result<Object> pageInstances(StdScheduleInstanceQueryDTO query) {
|
|
|
+ if (query == null) {
|
|
|
+ query = new StdScheduleInstanceQueryDTO();
|
|
|
+ }
|
|
|
+ Page<StdScheduleInstanceEntity> page = new Page<>(
|
|
|
+ query.getPageIndex() == null ? 1 : query.getPageIndex(),
|
|
|
+ query.getPageSize() == null ? 10 : query.getPageSize());
|
|
|
+ LambdaQueryWrapper<StdScheduleInstanceEntity> qw = new LambdaQueryWrapper<>();
|
|
|
+ if (query.getJobId() != null) {
|
|
|
+ qw.eq(StdScheduleInstanceEntity::getJobId, query.getJobId());
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(query.getJobKey())) {
|
|
|
+ qw.eq(StdScheduleInstanceEntity::getJobKey, query.getJobKey().trim());
|
|
|
+ }
|
|
|
+ if (StringUtils.hasText(query.getStatus())) {
|
|
|
+ qw.eq(StdScheduleInstanceEntity::getStatus, query.getStatus().trim());
|
|
|
+ }
|
|
|
+ qw.orderByDesc(StdScheduleInstanceEntity::getId);
|
|
|
+ return Result.result(stdScheduleInstanceMapper.selectPage(page, qw));
|
|
|
+ }
|
|
|
+
|
|
|
+ public Result<Object> listHandlers() {
|
|
|
+ Set<String> names = handlerRegistry.names();
|
|
|
+ return Result.result(names == null ? Collections.emptySet() : names);
|
|
|
+ }
|
|
|
+
|
|
|
+ public Result<Object> listNodes() {
|
|
|
+ List<StdScheduleNodeEntity> list = stdScheduleNodeMapper.selectList(
|
|
|
+ new LambdaQueryWrapper<StdScheduleNodeEntity>().orderByDesc(StdScheduleNodeEntity::getLastHeartbeat));
|
|
|
+ return Result.result(list);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 事务提交后再从 DB 重载缓存,避免读到未提交数据;无事务则立即重载。 */
|
|
|
+ private void reloadCacheAfterCommit(Long jobId) {
|
|
|
+ if (jobId == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
|
|
+ TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
|
|
+ @Override
|
|
|
+ public void afterCommit() {
|
|
|
+ jobCache.reloadById(jobId);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ } else {
|
|
|
+ jobCache.reloadById(jobId);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void reloadCacheAfterCommit(Collection<Long> jobIds) {
|
|
|
+ if (CollectionUtils.isEmpty(jobIds)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
|
|
+ TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
|
|
+ @Override
|
|
|
+ public void afterCommit() {
|
|
|
+ jobCache.reloadByIds(jobIds);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ } else {
|
|
|
+ jobCache.reloadByIds(jobIds);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|