SpringMVC框架使用註解執行定時任務

項目開發過程當中,免不了會有一些定時任務。今天就給你們一個SpringMVC框架中利用註解的方式執行定時任務的示例代碼php

使用到的JAR文件:

點擊下列Jar文件會跳到個人網盤下載html

aopalliance-1.0.jar
commons-logging-1.1.3.jar
spring-aop-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
spring-web-3.2.4.RELEASE.jar
spring-webmvc-3.2.4.RELEASE.jar前端

首先要配置咱們的SpringMVC文件

    xmlns 加下面的內容、java

xmlns:task="http://www.springframework.org/schema/task"

    而後xsi:schemaLocation加下面的內容、web

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd

    最後是咱們的task任務掃描註解spring

<!-- task任務掃描註解 -->
<task:annotation-driven/>

    我配置的掃描位置是express

<context:component-scan base-package="com.wuzhut"></context:component-scan>

下面寫出一個測試類

package com.wuzhut.task;

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

@Component
public class MyTask {
    @Scheduled(cron="0/5 * * * * ? ") //間隔5秒執行
    public void taskCycle(){
        System.out.println("無主題(www.wuzhuti.cn) <span style="color: #000000;">專一於前端開發技術和<span id="3_nwp" style="width: auto; height: auto; float: none;"><a id="3_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=18&is_app=0&jk=d1b169b675029816&k=%B3%CC%D0%F2%BF%AA%B7%A2&k0=%B3%CC%D0%F2%BF%AA%B7%A2&kdi0=0&luki=4&n=10&p=baidu&q=06003100_cpr&rb=0&rs=1&seller_id=1&sid=16980275b669b1d1&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1948625&u=http%3A%2F%2Fwuzhuti%2Ecn%2F850%2Ehtml&urlid=0" target="_blank" mpid="3" style="text-decoration: none;"><span style="color:#0000ff;font-size:12px;width:auto;height:auto;float:none;">程序開發</span></a></span>研究的技術博客</span>");
    }
}

注意

須要注意的幾點:mvc

一、spring的@Scheduled註解  須要寫在實現上、app

二、 定時器的任務方法不能有返回值(若是有返回值,spring初始化的時候會告訴你有個錯誤、須要設定一個proxytargetclass的某個值爲true、具體就去百度google吧)框架

三、實現類上要有組件的註解@Component

四、下面的文章連接是corn表達式、你們能夠參考一下

示例代碼下載地址

點擊下載

文章連接

quartz CronExpression表達式

相關文章
相關標籤/搜索