spring可配置定时器

深渊向深渊呼唤

1、初始化配置

package com.zhoulp.timer;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 
 * 
 * @Description 初始化配置
 * @author zhoulongpeng
 * @date   2020年1月14日 下午8:21:13
 *
 */
@Configuration
@EnableAsync
public class InitConfigurer implements WebMvcConfigurer {
	@Bean
	public TaskScheduler initTaskScheduler() {
		ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
		scheduler.setPoolSize(8);
		scheduler.setThreadNamePrefix("timer-task-");
		return scheduler;
	}
}

2、启动定时器

package com.zhoulp.timer.schedule;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.zhoulp.timer.ScheduleCronConstant;
import com.zhoulp.timer.ScheduleServicePool;

/**
 *
 * @Description
 * @author zhoulongpeng
 * @date   2020年1月14日 下午8:14:10
 *
 */
@Component("scheduleDynamicCronDemo")
public class ScheduleDynamicCronDemo implements TimerInterface {
	
	@Autowired
	private TaskScheduler taskScheduler;
	private ScheduledFuture<?> future;
	
	/**
	 * @Description 启动定时器
	 */
	@PostConstruct
	@Override
	public void start() {
		ScheduleServicePool.addTimer("demo1", this);
		restart(ScheduleCronConstant.DEMO_CRON1);
	}
	@Override
	public void restart(long period) {
		// 不需要实现
	}
	/**
	 * @Description 重启启动定时器
	 */
	@Override
	public void restart(String cron) {
		stop();
		future = taskScheduler.schedule(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println("timer1: begin call business code");
//					scheduleExport.scheduleTaskExport();// 异步定时生成文件
					System.out.println("timer1: end call business code");
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 定时任务触发,可修改定时任务的执行周期
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExecDate = trigger.nextExecutionTime(triggerContext);
				return nextExecDate;
			}
		});
	}
	@Override
	public void stop() {
		if (future != null) {
			future.cancel(true);// 取消任务调度
		}
	}
}
栏目