spring 的自动定时任务

spring的自动定时任务有两种

第一种:通过xml配置来设置

需要在xml中引入新的约束,并且需要配置<task:scheduled-tasks> ,主要配置内容如下:

<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd">
   <context:component-scan base-package="com.shsxt.timer"/>
    <task:scheduled-tasks>
        <task:scheduled ref="timer" method="mobileCode" cron="0/2 * * * * ?"/>
    </task:scheduled-tasks>
</beans>
<task:scheduled ref="timer" method="mobileCode" cron="0/2 * * * * ?"/>
ref的值等于类名的首字母小写,method的是类中的方法名 cron表达式表示定时多长时间,此时该值表示两秒,可以通过cron表达式在线生成器来获取定时任务对应的表达式

通过配置这些,该类中的方法的逻辑就可被定时的执行了

第二种通过注解来配置定时器,需要xml配置注解<task:annotation-driven>即可
<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd">
   <context:component-scan base-package="com.shsxt.timer"/>
    <task:annotation-driven></task:annotation-driven>
</beans>

在类中的方法上需要配置注解@Scheduled(cron =" 0/2 * * * * ?")

具体代码内容如下:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class Timer {
    @Scheduled(cron = "0/2 * * * * ? ")
    public void mobileCode(){
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" ).format(new Date()));
    }
}




原文地址:https://www.cnblogs.com/liu1459310172/p/9721326.html