Spring使用@Scheduled定时调度

时间:2023-03-09 00:16:45
Spring使用@Scheduled定时调度

一、spring配置文件中增加对这个注解的支持:

配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:task="http://www.springframework.org/schema/task"
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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.1.xsd">

<!-- 开启定时任务 -->
<task:annotation-driven />
<!-- 开启注解 -->
<context:annotation-config />
<!-- 指定相关的包路径 -->
<context:component-scan base-package="com.xxx.task"/>
 <!-- <bean id="myTask" class="com.xxx.task.MyTask" />
  <task:scheduled-tasks>
  <task:scheduled ref="myTask" method="uploadFileToFTP" cron="0 29 17 * * ?" />
  </task:scheduled-tasks> --><!-- 此处注释掉是因为测试注解的时候无效,所以使用xml配置测试,发现通过,发现MyTask类需要加上注解@EnableScheduling-->

</beans>

二、MyTask类文件需要以下两个注解

@Component("myTask")
@EnableScheduling

三、需要定时调度的方法需要以下注解,表达式根据自己需要配置

@Scheduled(cron="0 35 17 * * ?")