spring文件xml中添加 1.xmlns:task="http://www.springframework.org/schema/task" 2.xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd" 两种方式:注解和xml配置,推荐xml形式,方便管理 1.注解方式: (1).spring的文件添加<task:annotation-driven/>,开启定时任务扫描 (2).在class添加注解@Component,在方法添加注解@Scheduled(cron="0/2 * * * * ?") @Component("demoJob") public class DemoJob { private static final String className = DemoJob.class.getName(); // 每隔2秒执行 @Scheduled(cron="0/2 * * * * ?") public void job1(){ System.out.print(DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS)); System.out.println("------- == " + className + ".test1()-------"); } } 2.xml配置方式: springContext_task.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:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!-- 若在类中用@Component("demoJob")注解一下,则不需要下面的bean定义了 --> <bean id="demoJob" class="cn.yueworld.enrolment.task.DemoJob" /> <task:scheduled-tasks> <!-- 每隔xx执行 --> <task:scheduled ref="demoJob" method="job1" cron="0/2 * * * * ?" /> </task:scheduled-tasks> </beans>
spring定时任务
最新推荐文章于 2024-11-11 19:15:26 发布