针对elasticJob,在服务未完全启动的情况,通过拒绝执行方法来避免因为依赖service等组件未初始化完成,导致定时任务业务逻辑执行异常。

    1. public class ElasticJobState {
    2. public static Boolean JOB_STATE = Boolean.FALSE;
    3. public static void enable() {
    4. ElasticJobState.JOB_STATE = Boolean.TRUE;
    5. }
    6. public static void disable() {
    7. ElasticJobState.JOB_STATE = Boolean.FALSE;
    8. }
    9. }
    1. public class ElasticJobApplicationStartListener implements ApplicationListener<ApplicationStartedEvent> {
    2. @Override
    3. public void onApplicationEvent(ApplicationStartedEvent event) {
    4. log.info("elastic job start..................");
    5. ElasticJobState.enable();
    6. }
    7. }
    1. public class ElasticJobApplicationClosedListener implements ApplicationListener<ContextClosedEvent> {
    2. @Override
    3. public void onApplicationEvent(ContextClosedEvent event) {
    4. log.info("elastic job closed..................");
    5. ElasticJobState.disable();
    6. }
    7. }
    1. @Slf4j
    2. public abstract class XySimpleJob implements SimpleJob {
    3. @Override
    4. public void execute(ShardingContext shardingContext) {
    5. String jobName = shardingContext.getJobName();
    6. if (!ElasticJobState.JOB_STATE) {
    7. log.warn("The service is not ready and the scheduled task is rejected.............jobName:{}", jobName);
    8. return;
    9. }
    10. JobDescInfo jobDescInfo = getJobDescInfo();
    11. int shardingTotalCount = shardingContext.getShardingTotalCount();
    12. int shardingItem = shardingContext.getShardingItem();
    13. String taskId = shardingContext.getTaskId();
    14. log.info("jobName:{},shardingTotalCount:{},shardingItem:{},taskId:{}", jobName, shardingTotalCount, shardingItem, taskId);
    15. //调用执行目标方法
    16. executeJob(shardingContext);
    17. }
    18. protected abstract void executeJob(ShardingContext shardingContext);
    19. protected abstract JobDescInfo getJobDescInfo();
    20. }

    cat监控同理