Open-Starter-Schedule

一个基于时间轮算法实现的任务调度组件

🍪 快速开始

欢迎阅读 Open-Starter-Schedule 文档!

如果你有任何与 Open-Starter-Schedule 相关的问题,欢迎随时在 GitHub Discussions 上向我们的社区寻求帮助。

系统环境需求

1. 添加 Maven 依赖

<dependency>
    <groupId>com.saucesubfresh</groupId>
    <artifactId>open-starter-schedule</artifactId>
    <version>1.1.1</version>
</dependency>

2. 配置参数

com:
  saucesubfresh:
    schedule:
      # 配置时间轮槽数
      tick-duration: 60

3. 实现调度任务服务接口

实现 ScheduleTaskService 接口,在项目启动时会全量同步调度任务到 TimeWheel

节选自 Open-Job

@Service
public class OpenJobServiceImpl extends ServiceImpl<OpenJobMapper, OpenJobDO> implements OpenJobService, ScheduleTaskService {

    private final TimeWheel timeWheel;
    private final OpenJobMapper openJobMapper;
    private final OpenJobClientService openJobClientService;
    private final ScheduleTaskExecutor scheduleTaskExecutor;

    public OpenJobServiceImpl(TimeWheel timeWheel,
                              OpenJobMapper openJobMapper,
                              OpenJobClientService openJobClientService,
                              ScheduleTaskExecutor scheduleTaskExecutor) {
        this.timeWheel = timeWheel;
        this.openJobClientService = openJobClientService;
        this.openJobMapper = openJobMapper;
        this.scheduleTaskExecutor = scheduleTaskExecutor;
    }

    //~~~

    @Override
    public boolean start(Long id) {
        OpenJobDO openJobDO = openJobMapper.selectById(id);
        openJobDO.setStatus(CommonStatusEnum.YES.getValue());
        openJobDO.setUpdateTime(LocalDateTime.now());
        openJobMapper.updateById(openJobDO);
        ScheduleTask scheduleTask = createScheduleTask(openJobDO);
        timeWheel.put(scheduleTask.getTaskId(), scheduleTask.getCronExpression());
        return Boolean.TRUE;
    }

    @Override
    public List<ScheduleTask> loadTask() {
        List<OpenJobDO> scheduleTasks = openJobMapper.queryStartJob();
        if (CollectionUtils.isEmpty(scheduleTasks)){
            return Collections.emptyList();
        }
        return scheduleTasks.stream().map(this::createScheduleTask).collect(Collectors.toList());
    }

    @Override
    public ScheduleTask get(Long id) {
        OpenJobDO openJobDO = openJobMapper.selectById(id);
        if (CommonStatusEnum.of(openJobDO.getStatus()) == CommonStatusEnum.NO){
            return null;
        }
        return createScheduleTask(openJobDO);
    }

    //~~~
}

注意

若要支持多节点同时调度任务不重复执行,可基于分布式锁实现