Java Spring分别实现定时任务方法

目录
  • java实现定时任务
    • Timer+TimerTask
    • 示例
    • 弊端
    • ScheduledThreadPoolExecutor
    • 示例
  • Spring定时任务
    • 示例
    • 原理

java实现定时任务

Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor

Timer+TimerTask

创建一个Timer就创建了一个线程,可以用来调度TimerTask任务

Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。

主要有三个比较重要的方法:

cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响

purge():从任务队列中移除所有已经取消的任务

schedule:开始调度任务,提供了几个重载方法:

schedule(TimerTask task, long delay)延时执行,表示delay毫秒后执行一次task任务

schedule(TimerTask task, Date time)`指定时间执行,到`time`时间的时候执行一次`task
schedule(TimerTask task, long delay, long period)`延时周期执行,经过`delay`毫秒后每`period`毫秒执行一次`task
schedule(TimerTask task, Date firstTime, long period)`指定时间后周期执行,到达指定时间`firstTime`后每`period`毫秒执行一次`task

示例

public class TimerTest {
    public static void main(String[] args) {
        Timer timer = new Timer("aa");
        Task task = new Task();
        timer.schedule(task,new Date(),1000);
    }
}
class Task extends TimerTask{
    @Override
    public void run() {
        System.out.println(new Date());
    }
}

输出:
Thu Jul 07 14:50:02 CST 2022
Thu Jul 07 14:50:03 CST 2022
Thu Jul 07 14:50:04 CST 2022
Thu Jul 07 14:50:05 CST 2022
…………

弊端

Timer是单线程的,并且不会抛出异常,一旦定时任务抛出异常,将会导致整个线程停止,即定时任务停止。

ScheduledThreadPoolExecutor

因为Timer的缺陷,所以不建议使用Timer,建议使用ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutorTimer的替代者,于JDK1.5引入,继承了ThreadPoolExecutor,是基于线程池设计的定时任务类。

主要的调度方法:

schedule只执行一次调度,(任务,延迟时间,延迟时间单位)

scheduleAtFixedRate按固定的频率调度,如果执行时间过长,下次调度会延迟,(任务,第一次执行的延迟时间,周期,时间单位)

scheduleWithFixedDelay延迟调度,一次任务执行完后加上延迟时间执行下一次任务,(任务,第一次执行的延迟时间,间隔时间,时间单位)

示例

public class TimerTest {
    public static void main(String[] args) throws Exception{
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        scheduledExecutorService.scheduleAtFixedRate(
                () -> System.out.println(new Date()),
                1,3, TimeUnit.SECONDS);
    }
}

Spring定时任务

Spring定时任务主要靠@Scheduled注解实现,corn,fixedDelay,fixedDelayString,fixedRate,fixedRateString五个参数必须指定其一,传两个或三个都会抛出异常

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
	String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED;
    // cron表达式
	String cron() default "";
    // 时区
	String zone() default "";
    // 从上一次调用结束到下一次调用之间的固定时间
	long fixedDelay() default -1;
    // 和fixedDelay意思相同,只是使用字符传格式,支持占位符。例如:fixedDelayString = "${time.fixedDelay}"
	String fixedDelayString() default "";
    // 两次调用之间固定的毫秒数(不需要等待上次任务完成)
	long fixedRate() default -1;
    // 同上,支持占位符
	String fixedRateString() default "";
    // 第一次执行任务前延迟的毫秒数
	long initialDelay() default -1;
    // 同上,支持占位符
	String initialDelayString() default "";
}

示例

@Component
@EnableScheduling
public class ScheduledTask {
    @Scheduled(fixedDelay = 1000)
    public void task(){
        System.out.println("aaa");
    }
}

原理

项目启动ScheduledAnnotationBeanPostProcessorpostProcessAfterInitialization()方法扫描带有@Scheduled注解的方法:

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler ||
				bean instanceof ScheduledExecutorService) {
			// Ignore AOP infrastructure such as scoped proxies.
			return bean;
		}
		Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
		if (!this.nonAnnotatedClasses.contains(targetClass) &&
				AnnotationUtils.isCandidateClass(targetClass, Arrays.asList(Scheduled.class, Schedules.class))) {
			Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
					(MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> {
						Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
								method, Scheduled.class, Schedules.class);
						return (!scheduledMethods.isEmpty() ? scheduledMethods : null);
					});
			if (annotatedMethods.isEmpty()) {
				this.nonAnnotatedClasses.add(targetClass);
				if (logger.isTraceEnabled()) {
					logger.trace("No @Scheduled annotations found on bean class: " + targetClass);
				}
			}
			else {
				// Non-empty set of methods
				annotatedMethods.forEach((method, scheduledMethods) ->
                        // 调用processScheduled方法将定时任务的方法存放到任务队列中
						scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean)));
				if (logger.isTraceEnabled()) {
					logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName +
							"': " + annotatedMethods);
				}
			}
		}
		return bean;
	}
	protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
		try {
            // 创建任务线程
			Runnable runnable = createRunnable(bean, method);
            // 解析到定时任务方式的标记,解析到正确的参数后会设置为TRUE,如果在解析到了其他的参数就会抛出异常
			boolean processedSchedule = false;
			String errorMessage =
					"Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required";
			Set<ScheduledTask> tasks = new LinkedHashSet<>(4);
			// Determine initial delay 解析第一次的延迟(解析initialDelay参数)
			long initialDelay = scheduled.initialDelay();
			String initialDelayString = scheduled.initialDelayString();
			if (StringUtils.hasText(initialDelayString)) {
                // initialDelay不能小于0
				Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both");
				if (this.embeddedValueResolver != null) {
					initialDelayString = this.embeddedValueResolver.resolveStringValue(initialDelayString);
				}
				if (StringUtils.hasLength(initialDelayString)) {
					try {
						initialDelay = parseDelayAsLong(initialDelayString);
					}
					catch (RuntimeException ex) {
						throw new IllegalArgumentException(
								"Invalid initialDelayString value \"" + initialDelayString + "\" - cannot parse into long");
					}
				}
			}
			// Check cron expression 解析cron表达式
			String cron = scheduled.cron();
			if (StringUtils.hasText(cron)) {
                // 解析时区
				String zone = scheduled.zone();
				if (this.embeddedValueResolver != null) {
					cron = this.embeddedValueResolver.resolveStringValue(cron);
					zone = this.embeddedValueResolver.resolveStringValue(zone);
				}
				if (StringUtils.hasLength(cron)) {
					Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");
					processedSchedule = true;
					if (!Scheduled.CRON_DISABLED.equals(cron)) {
						TimeZone timeZone;
						if (StringUtils.hasText(zone)) {
							timeZone = StringUtils.parseTimeZoneString(zone);
						}
						else {
							timeZone = TimeZone.getDefault();
						}
						tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));
					}
				}
			}
            // 第一次延迟参数小于0,默认为0
			// At this point we don't need to differentiate between initial delay set or not anymore
			if (initialDelay < 0) {
				initialDelay = 0;
			}
			// Check fixed delay 解析fixedDelay参数
			long fixedDelay = scheduled.fixedDelay();
			if (fixedDelay >= 0) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay)));
			}
			String fixedDelayString = scheduled.fixedDelayString();
			if (StringUtils.hasText(fixedDelayString)) {
				if (this.embeddedValueResolver != null) {
					fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString);
				}
				if (StringUtils.hasLength(fixedDelayString)) {
					Assert.isTrue(!processedSchedule, errorMessage);
					processedSchedule = true;
					try {
						fixedDelay = parseDelayAsLong(fixedDelayString);
					}
					catch (RuntimeException ex) {
						throw new IllegalArgumentException(
								"Invalid fixedDelayString value \"" + fixedDelayString + "\" - cannot parse into long");
					}
					tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay)));
				}
			}
			// Check fixed rate 解析fixedRate参数
			long fixedRate = scheduled.fixedRate();
			if (fixedRate >= 0) {
				Assert.isTrue(!processedSchedule, errorMessage);
				processedSchedule = true;
				tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay)));
			}
			String fixedRateString = scheduled.fixedRateString();
			if (StringUtils.hasText(fixedRateString)) {
				if (this.embeddedValueResolver != null) {
					fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString);
				}
				if (StringUtils.hasLength(fixedRateString)) {
					Assert.isTrue(!processedSchedule, errorMessage);
					processedSchedule = true;
					try {
						fixedRate = parseDelayAsLong(fixedRateString);
					}
					catch (RuntimeException ex) {
						throw new IllegalArgumentException(
								"Invalid fixedRateString value \"" + fixedRateString + "\" - cannot parse into long");
					}
					tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay)));
				}
			}
			// Check whether we had any attribute set
            // 如果五个参数一个也没解析到,抛出异常
			Assert.isTrue(processedSchedule, errorMessage);
			// Finally register the scheduled tasks
            // 并发控制将任务队列存入注册任务列表
			synchronized (this.scheduledTasks) {
				Set<ScheduledTask> regTasks = this.scheduledTasks.computeIfAbsent(bean, key -> new LinkedHashSet<>(4));
				regTasks.addAll(tasks);
			}
		}
		catch (IllegalArgumentException ex) {
			throw new IllegalStateException(
					"Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage());
		}
	}

将任务解析并添加到任务队列后,交由ScheduledTaskRegistrar类的scheduleTasks方法添加(注册)定时任务到环境中

protected void scheduleTasks() {
   if (this.taskScheduler == null) {
       //获取ScheduledExecutorService对象,实际上都是使用ScheduledThreadPoolExecutor执行定时任务调度
      this.localExecutor = Executors.newSingleThreadScheduledExecutor();
      this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
   }
   if (this.triggerTasks != null) {
      for (TriggerTask task : this.triggerTasks) {
         addScheduledTask(scheduleTriggerTask(task));
      }
   }
   if (this.cronTasks != null) {
      for (CronTask task : this.cronTasks) {
         addScheduledTask(scheduleCronTask(task));
      }
   }
   if (this.fixedRateTasks != null) {
      for (IntervalTask task : this.fixedRateTasks) {
         addScheduledTask(scheduleFixedRateTask(task));
      }
   }
   if (this.fixedDelayTasks != null) {
      for (IntervalTask task : this.fixedDelayTasks) {
         addScheduledTask(scheduleFixedDelayTask(task));
      }
   }
}
private void addScheduledTask(@Nullable ScheduledTask task) {
   if (task != null) {
      this.scheduledTasks.add(task);
   }
}

到此这篇关于Java Spring分别实现定时任务方法的文章就介绍到这了,更多相关Java 定时任务内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Java之SpringBoot定时任务案例讲解

    1. SpringBoot--任务:定时任务 项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候, 分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了 两个接口和两个注解,并且用corn表达式去定时. TaskScheduler //任务调度程序 TaskExecutor //任务执行者 @EnableScheduling //开启定时功能的注解,放在主入口 @Scheduled //什么时候执行 cron表达式 1.1 编写定时任务的方法 我们里面存在一

  • java中 spring 定时任务 实现代码

    复制代码 代码如下: import org.apache.log4j.*;public class TaskJob {       public static Logger log = Logger                     .getLogger(TaskJob.class);       public void SayHello() {              // TODO Auto-generated method stub              try {      

  • 最流行的java后台框架spring quartz定时任务

    配置quartz 在spring中需要三个jar包: quartz-1.8.5.jar.commons-collections-3.2.1.jar.commons-logging-1.1.jar 首先要配置我们的spring.xml xmlns 多加下面的内容. xmlns:task="http://www.springframework.org/schema/task" 然后xsi:schemaLocation多加下面的内容. http://www.springframework.o

  • 一文搞懂如何实现Java,Spring动态启停定时任务

    目录 为什么需要定时任务 Java定时任务的原理 Timer+TimerTask ScheduledThreadPoolExecutor Timer VS ScheduledThreadPoolExecutor Spring定时任务 @Scheduled定时任务原理(源码) 为什么需要定时任务 定时任务的应用场景十分广泛,如定时清理文件.定时生成报表.定时数据同步备份等. Java定时任务的原理 jdk自带的库中,有两种技术可以实现定时任务,一种是Timer,另一种是ScheduledThrea

  • java 中Spring task定时任务的深入理解

    java 中Spring task定时任务的深入理解 在工作中有用到spring task作为定时任务的处理,spring通过接口TaskExecutor和TaskScheduler这两个接口的方式为异步定时任务提供了一种抽象.这就意味着spring容许你使用其他的定时任务框架,当然spring自身也提供了一种定时任务的实现:spring task.spring task支持线程池,可以高效处理许多不同的定时任务.同时,spring还支持使用Java自带的Timer定时器和Quartz定时框架.

  • Java下SpringBoot创建定时任务详解

    序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了. 三.基于注解设定多线程定时任务 一.静态:基于注解 基于注解@Scheduled默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响. 1.创建定时器 使用SpringBoo

  • Java spring定时任务详解

    目录 一.定时任务 1.cron表达式 2.cron示例 3.SpringBoot整合 总结 一.定时任务 1.cron表达式 语法:秒 分 时 日 月 周 年 (其中"年"Spring不支持,也就是说在spring定时任务中只能设置:秒 分 时 日 月 周) 2.cron示例 3.SpringBoot整合 @EnableScheduling @Scheduled 实例: package com.xunqi.gulimall.seckill.scheduled; import lomb

  • Java Spring分别实现定时任务方法

    目录 java实现定时任务 Timer+TimerTask 示例 弊端 ScheduledThreadPoolExecutor 示例 Spring定时任务 示例 原理 java实现定时任务 Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor. Timer+TimerTask 创建一个Timer就创建了一个线程,可以用来调度TimerTask任务 Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线

  • Java中实现分布式定时任务的方法

    定时器Scheduler在平时使用比较频繁,在springboot中,配置好@Scheduled和@EnableScheduling之后,定时器就能正常执行,实现定时任务的功能. 但是在这样的情况下:如果开发的服务需要水平部署实现负载均衡,那么定时任务就会同时在多个服务实例上运行,那么一方面,可能由于定时任务的逻辑处理需要访问公共资源从而造成并发问题:另一方面,就算没有并发问题,那么一个同样的任务多个服务实例同时执行,也会造成资源的浪费.因此需要一种机制来保证多个服务实例之间的定时任务正常.合理

  • Java Spring Controller 获取请求参数的几种方法详解

    Java Spring Controller 获取请求参数的几种方法  1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交.若"Content-Type"="application/x-www-form-urlencoded",可用post提交 url形式:http://localhost:8080/SSMDemo/demo/addUser1?username=lixiaoxi&password=1

  • Java Spring MVC 上传下载文件配置及controller方法详解

    下载: 1.在spring-mvc中配置(用于100M以下的文件下载) <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!--配置下载返回类型--> <bean class="or

  • Java Web实现添加定时任务的方法示例

    本文实例讲述了Java Web实现添加定时任务的方法.分享给大家供大家参考,具体如下: 定时任务时间控制类 /** * 定时任务时间控制 * * @author liming * */ public class TimerManager { // 时间间隔 private static final long PERIOD_DAY = 24 * 60 * 60 * 1000; public TimerManager() { Calendar calendar = Calendar.getInsta

  • Java Spring项目国际化(i18n)详细方法与实例

    Spring国际化概述 国际化基本规则 国际化信息"也称为"本地化信息",一般需要两个条件才可以确定一个特定类型的本地化信息,它们分别是"语言类型"和"国家/地区的类型".如中文本地化信息既有中国大陆地区的中文,又有中国台湾.中国香港地区的中文,还有新加坡地区的中文.Java通过java.util.Locale类表示一个本地化对象,它允许通过语言参数和国家/地区参数创建一个确定的本地化对象. 语言参数使用ISO标准语言代码表示,这些代码

  • 详解spring多线程与定时任务

    本篇主要描述一下spring的多线程的使用与定时任务的使用. 1.spring多线程任务的使用 spring通过任务执行器TaskExecutor来实现多线程与并发编程.通常使用ThreadPoolTaskExecutor来实现一个基于线程池的TaskExecutor. 首先你要实现AsyncConfigurer 这个接口,目的是开启一个线程池 代码如下: package com.foreveross.service.weixin.test.thread; import java.util.co

  • Spring Boot @Scheduled定时任务代码实例解析

    假设我们已经搭建好了一个基于Spring Boot项目,首先我们要在Application中设置启用定时任务功能@EnableScheduling. 启动定时任务 package com.scheduling; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframewo

  • JAVA使用quartz添加定时任务,并依赖注入对象操作

    最近在写定时任务,以前没接触过.查了些相关资料说使用quartz定时框架. 需要配置文件:config-quartz.xml 相关配置如下(红色部分是之后添加的,在后面步骤会说明): <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www

随机推荐