Loading
0

spring中的定时任务

参考:

通过配置来加入任务:

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

@Slf4j
@Configuration
@EnableScheduling
public class SchedulingConfigurer implements org.springframework.scheduling.annotation.SchedulingConfigurer {

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        CronTask cronTask = new CronTask(() -> {
        }, "0/1 * * * * ?");
        taskRegistrar.addCronTask(cronTask);
    }
}

通过ThreadPoolTaskScheduler加入任务:

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Service;
import yhzh.meter.copy.common.task.McsCronTask;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@Service
public class MeterCopyTaskManager implements DisposableBean {

    private final ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private final Map<String, ScheduledFuture<?>> scheduledFutureMap = new ConcurrentHashMap<>(16);

    @Autowired
    public MeterCopyTaskManager(ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        this.threadPoolTaskScheduler = threadPoolTaskScheduler;
    }

    @Override
    public void destroy() {
        for (ScheduledFuture<?> scheduledFuture : this.scheduledFutureMap.values()) {
            scheduledFuture.cancel(true);
        }
        scheduledFutureMap.clear();
    }

    /**
     * 启动定时任务
     */
    public void startTask(McsCronTask mcsCronTask) {
        CronTask cronTask = new CronTask(mcsCronTask, mcsCronTask.getCronExpression());
        ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        if (ObjectUtil.isNotNull(scheduledFuture)) {
            scheduledFutureMap.put(mcsCronTask.getObjectId(), scheduledFuture);
        }
    }

    /**
     * 停止定时任务
     */
    public void stopTask(String objectId) {
        ScheduledFuture<?> scheduledFuture = scheduledFutureMap.get(objectId);
        if (ObjectUtil.isNotNull(scheduledFuture)) {
            scheduledFuture.cancel(true);
            scheduledFutureMap.remove(objectId);
        }
    }

最后编辑于:2022/3/17作者: joycode

评论已关闭