定时任务 ThreadPoolTaskScheduler的使用

// 方法1

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Configuration
public class TaskConfig {

    // 线程存储器
    public static ConcurrentHashMap<String, ScheduledFuture> SCHEDULE = new ConcurrentHashMap<String, ScheduledFuture>();

    // 创建线程
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler taskScheduler= new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(20);
        taskScheduler.setThreadNamePrefix("taskExecutor-");
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.setAwaitTerminationSeconds(60);
        return taskScheduler;
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;

@Controller
public class TaskController {

    @Autowired
    private ThreadPoolTaskScheduler taskSchedule;

    /**
     * 定时任务
     * @param dateTime 指定时间
     */
    @RequestMapping(value = "/schedule", method = RequestMethod.POST)
    @ResponseBody
    public String schedule(String dateTime) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cron = getCron(sdf.parse(dateTime));
        ScheduledFuture<?> future = taskSchedule.schedule(() -> {
            //处理业务
            System.out.println("到时间啦!");

        }, new CronTrigger(cron));

        if(future == null){
            System.out.println("服务异常!");
            return "服务异常!";
        }else{
            TaskConfig.SCHEDULE.put("1", future);
            System.out.println("执行成功!");
        }
        return "执行成功!";
    }

    /**
     * 删除
     * @param id key
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(String id) {
        /*
         * 关于Future.cancel(false)
         * Future接口用于获取异步计算的结果,可通过get()获取结果、cancel()取消、isDone()判断是否完成等操作。
         * 传入true会中断线程停止任务,传入false则会让线程正常执行至完成。
         */
        boolean cancel = TaskConfig.SCHEDULE.get(id).cancel(false);
        if(cancel){
            TaskConfig.SCHEDULE.remove(id);
        }
        
        return "执行成功!";
    }


    /**
     * 日期转换cron表达式
     * @param date  日期
     * @return
     */
    public static String getCron(Date date) {
        String dateFormat = "ss mm HH dd MM ?";
        return formatDate(date, dateFormat);
    }

    public static String formatDate(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTime = null;
        if (date != null) {
            formatTime = sdf.format(date);
        }
        return formatTime;
    }
}

//方法2

	// 线程存储器
	public static ConcurrentHashMap<String, Timer> SCHEDULE = new ConcurrentHashMap<String, Timer>();
	
	/**
	 * 定时任务
	 * @param dateTime 指定时间
	 */
	@RequestMapping(value = "/schedule2", method = RequestMethod.POST)
	@ResponseBody
	public String schedule2(String dateTime) throws ParseException {
	    Timer timer = new Timer();
	    TimerTask task = new TimerTask() {
	        @Override
	        public void run() {
	            //处理业务
	            System.out.println("到时间啦!");
	        }
	    };
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Date date = sdf.parse(dateTime);
	    timer.schedule(task, date);
	    SCHEDULE.put("1", timer);
	    System.out.println("执行成功!");
	
	    return "执行成功!";
	}
	
	/**
	 * 删除
	 * @param id key
	 */
	@RequestMapping(value = "/delete2", method = RequestMethod.POST)
	@ResponseBody
	public String delete2(String id) {
	    Timer timer = SCHEDULE.get(id);
	    timer.cancel();
	    SCHEDULE.remove(id);
	
	    return "执行成功!";
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值