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);// 取消任務調度
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章