任务加载器

任务加载器,顾名思义,就是负责加载任务,可以从数据库加载,也可以从其他储存介质中加载。

public interface ScheduleTaskService {

    /**
     * 获取即将被调度的任务
     * @return 调度任务集合
     */
    ScheduleTask get(Long taskId);

    /**
     * 从数据库获取启动状态的全部任务
     * @return 任务池中存在的全部任务
     */
    Collection<ScheduleTask> loadTask();
}

以下是一个从数据库加载任务的例子,代码节选自 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 ScheduleTask get(Long id) {
        OpenJobDO openJobDO = openJobMapper.selectById(id);
        if (CommonStatusEnum.of(openJobDO.getStatus()) == CommonStatusEnum.NO){
            return null;
        }
        return createScheduleTask(openJobDO);
    }

    @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());
    }

    //~~~
}