spring定时任务

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值