springboot定时任务

1.启动类开启//@EnableScheduling注解或者是在配置类中开启

package com.springboot.schduling;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@SpringBootConfiguration
public class SchdulingConfiguration implements SchedulingConfigurer,AsyncConfigurer {
	  //将线程池注册到异步任务中
		@Override
		public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
			TaskScheduler   asyncExecutor = getAsyncExecutor();
			taskRegistrar.setTaskScheduler(asyncExecutor);
			
		}
		//创建定时任务线程池
		@Override
		@Bean()
		public ThreadPoolTaskScheduler  getAsyncExecutor() {
			ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
			scheduler.setPoolSize(3);
			//线程名称,设置好了之后可以方便我们定位处理任务所在的线程池
			scheduler.setThreadNamePrefix("Lyj-task-");
			//该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
			scheduler.setAwaitTerminationSeconds(60);
			//用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
			scheduler.setWaitForTasksToCompleteOnShutdown(true);
			return scheduler;
		}
		
		/*
		* 异步任务 异常处理
		*/
		@Override
		public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
		{
		return new SimpleAsyncUncaughtExceptionHandler();
		}
		
}

服务启动,会自动执行以下方法

package com.springboot.schduling;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SchdulingTask{
	private   static final SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedRate=3000)
	public  void schdulingTask() {
		String threadName = Thread.currentThread().getName();
		System.out.println("当前线程名字是"+threadName+"每隔三秒执行一次定时任务"+dataFormat.format(new Date()));
	}
  
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值