Nacos配置定时任务的开关

定义ScheduledProperties

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@Getter
@Setter
@ConfigurationProperties(prefix = "pic-scheduling")
public class ScheduledProperties{

    private Boolean enable = true;

    private String taskCronTrigger;

}

配置定时任务

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;

@Component
@Slf4j
public class ScheduledTask implements InitializingBean {

    private static ScheduledFuture<?> future = null;

    private ThreadPoolTaskScheduler  threadPoolTaskScheduler;

    @Resource
    private ScheduledProperties scheduledProperties;

    private static final String SCHEDULED_PREFIX = "pic-scheduling";

    /**
     * 监听定时任务配置
     */
    @EventListener
    public void envChangeListener(EnvironmentChangeEvent event) {
        Set<String> keys = event.getKeys();
        if (CollectionUtils.isNotEmpty(keys)) {
            // 判断是否修改了定时任务的配置
            boolean flag = keys.stream().anyMatch(x -> x.startsWith(SCHEDULED_PREFIX));
            if (flag) {
                log.info("The configuration of the scheduled task is changed. Procedure");
                // 若已存在该定时任务,则停止重新创建
                if (Objects.nonNull(future)) {
                    future.cancel(true);
                }
                this.syncExec();
            }
        }
    }

    /**
     * 创建定时任务
     */
    public void syncExec() {
        log.info("pic-scheduling.enable: {}", scheduledProperties.getEnable());
        if (Objects.equals(scheduledProperties.getEnable(), true)) {
            future = threadPoolTaskScheduler.schedule(() -> {
                try {
                   log.info("开始执行定时任务");
                } catch (Exception e) {
                    log.error("定时任务执行异常:", e);
                }
            }, triggerContext -> {
                String cron = scheduledProperties.getTaskCronTrigger();
                if (StringUtils.isEmpty(cron)) {
                    cron = "0 0/30 * * * ? "; //默认配置:每30分钟执行一次
                }
                return new CronTrigger(cron).nextExecutionTime(triggerContext);
            });
        } else {
            log.info("Canceling a scheduled task");
            if (Objects.nonNull(future)) {
                future.cancel(true);
            }
        }
    }

    @Override
    public void afterPropertiesSet() {
        taskScheduler();
        this.syncExec();
    }

    public void taskScheduler() {
        if (threadPoolTaskScheduler == null) {
            // 自定义线程池
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setPoolSize(3);
            scheduler.setThreadNamePrefix("picture-thread");
            scheduler.setAwaitTerminationSeconds(600);
            scheduler.setWaitForTasksToCompleteOnShutdown(true);
            threadPoolTaskScheduler = scheduler;
            threadPoolTaskScheduler.initialize();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值