java定时任务线程池动态添加,移除任务

该文章展示了如何在JavaSpring框架中配置线程池来处理定时任务,使用ThreadPoolTaskScheduler进行任务调度,并通过ConcurrentHashMap管理任务队列,支持添加和取消任务。定时任务的触发基于CronTrigger,且提供了任务的动态添加与移除功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、配置线程池

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 定时任务线程池配置类
 * @author 
 * @Date
 */
@Configuration
public class AsyncTheadConfig {
  
  @Bean("threadPoolTaskScheduler")
  public ThreadPoolTaskScheduler getThreadPoolTaskScheduler(){
    // 定时任务线程池
    ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
    // 线程池大小
    executor.setPoolSize(10);
    // 线程执行前缀
    executor.setThreadNamePrefix("ThreadPoolTaskScheduler-");
    // executor.setWaitForTasksToCompleteOnShutdown(true);
    // executor.setAwaitTerminationSeconds(60);
    executor.initialize();
    return executor;
  }  
}

二、建立需要运行的定时任务

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/index")
@RestController
public class IndexController1 {

  // 定时任务线程池
  @Autowired
  private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    
  // 任务队列管理
  @SuppressWarnings("rawtypes")
  private ConcurrentHashMap<String, ScheduledFuture> futureMap = new ConcurrentHashMap<String, ScheduledFuture>();
    
   
  // 加入新的任务进来
  @SuppressWarnings({ "rawtypes" })
  @GetMapping("/insert/{uid}/{time}")
  public Object insert(@PathVariable("uid") String uid, @PathVariable("time") String time){
      // 定时任务执行类
      TimerThread timerCollectData = new TimerThread(uid);
      // 通过ThreadPoolTaskScheduler类,设定定时时间
      ScheduledFuture future = threadPoolTaskScheduler.schedule(timerCollectData, new CronTrigger("*/"+time+" * * * * ?"));
      // 加入到队列中
      futureMap.put(uid, future);
      return null;
  }
    
  // 移除已有的一个任务
  @SuppressWarnings("rawtypes")
  @GetMapping("/remove/{uid}")
  public Object remove(@PathVariable("uid") String uid){
      ScheduledFuture scheduledFuture = futureMap.get(uid);
      if(scheduledFuture != null){
         // 取消定时任务
         scheduledFuture.cancel(true);
         // 如果任务取消需要消耗点时间
         boolean cancelled = scheduledFuture.isCancelled();
          while (!cancelled) {

                scheduledFuture.cancel(true);
                System.out.println(uid + "取消中");
          }
          // 最后从队列中删除
          futureMap.remove(uid);
      }
      return null;
    }
}

2.ok了!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值