spring---定时任务(@Scheduled注解)

来源:互联网 发布:企业java编程思想 pdf 编辑:程序博客网 时间:2024/06/03 18:41

在springMVC里面使用定时任务

(一)在xml里加入task的命名空间

<beans xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation=http://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task.xsd">

(二)启用注解驱动的定时任务<!-- Spring定时任务配置 -->
 

  <task:annotation-driven />


(三)配置定时任务的线程池(多任务时会用到)

<task:scheduler id="myScheduler" pool-size="5"/>

(四)写我们的定时任务

@Scheduled注解为定时任务,cron表达式里写执行的时机


任务一:

import java.text.DateFormat;import java.text.SimpleDateFormat;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Component//(把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)public class ATaskTest {//每10秒执行一次@Scheduled(cron="0/10 * *  * * ? ")public void Atask(){DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            System.out.println(sdf.format(System.currentTimeMillis())+"*********A任务每10秒执行一次进入测试"); }}

任务二:

package gt.task;import java.text.DateFormat;import java.text.SimpleDateFormat;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class BTaskTest {//每5秒执行一次@Scheduled(cron="0/5 * *  * * ?")public void bTask(){DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");System.out.println(sdf.format(System.currentTimeMillis())+"*********B任务每5秒执行一次进入测试");   }}
cron表达式待续。。。


阅读全文
0 0
原创粉丝点击