Spring 定时任务

Jacky Java 2021-11-23 37

启动定时任务

普通sping项目中 spring.xml 文件需要开启注解扫描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:task="http://www.springframework.org/schema/task" 
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task    
http://www.springframework.org/schema/task/spring-task-3.0.xsd">

	<!-- 加载定时器类 -->
	<context:component-scan base-package="com.yy" />

	<!--
	id:当配置多个executor时,被@Async("id")指定使用;也被作为线程名的前缀。
	pool-size:最大最小线程数
	core size:最小的线程数。缺省:1
	max size: 最大的线程数,缺省:Integer.MAX_VALUE
	queue-capacity:当最小的线程数已经被占用满后,新的任务会被放进queue里面,当这个queue的capacity也被占满之后,pool里面会创建新线程处理这个任务。直到总线程数达到了max size,这时系统会拒绝这个任务并抛出TaskRejectedException异常(缺省配置的情况下,能够通过rejection-policy来决定怎样处理这样的情况)。缺省值为:Integer.MAX_VALUE
	keep-alive:超过core size的那些线程,任务完毕后,再经过这个时长(秒)会被结束掉
rejection-policy:当pool已经达到max size的时候,怎样处理新任务
	ABORT(缺省):抛出TaskRejectedException异常,然后不运行
	DISCARD:不运行,也不抛出异常
	DISCARD_OLDEST:丢弃queue中最旧的那个任务
	CALLER_RUNS:不在新线程中运行任务,而是由调用者所在的线程来运行
	-->

	<task:annotation-driven executor="asyncExct" scheduler="scheduler" />
    <task:executor id="asyncExct"
               pool-size="5-10"
               queue-capacity="1"
			   keep-alive="60"
               rejection-policy="CALLER_RUNS"/>
	<task:scheduler id="scheduler" pool-size="1" />

</beans>

springboot 项目中只需要在启动类上添加注解 @EnableScheduling 即可定时任务功能

使用

注解方式 @Scheduled

@Component
@EnableScheduling
public class yyTask {
    @Scheduled(cron = "0/5 * * * * ? ") 
    public void yy() {
        // 间隔5秒执行
        System.out.println("----定时任务开始执行-----");
        System.out.println("----定时任务执行结束-----");
    }
}

实现接口 SchedulingConfigurer

@Slf4j
@Component
@EnableScheduling
public class PullEmailBlogTask implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(doTask(), getTrigger());
    }

    /**
     * 业务逻辑
     */
    private Runnable doTask() {
        return () -> {
            System.out.println("----定时任务开始执行-----");
            System.out.println("----定时任务执行结束-----");
        };
    }

    /**
     * 触发器
     */
    private Trigger getTrigger() {
        return triggerContext -> new CronTrigger(getCron()).nextExecutionTime(triggerContext);
    }

    /**
     * 规则
     */
    private String getCron() {
        return "0 0/10 * * * ?";
    }
}