Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Spring定時任務[不定時添加任務]

Spring定時任務[不定時添加任務]

編輯:關於Android編程

這裡講敘這進在工作上用的到Spring任務。

在項目中,我們需要定時任務來發送微博。當我添加微博後,選擇指定的時間發送微博信息時,我們需要添加一個任務[這裡是不定時的添加任務],下面的代碼就是實現這個功能。

這裡我們需要用到Spring的jar包,如果Spring中不包含quartz.jar包,我們這需要下載,然後引用。

下面為web.xml的配置:

01
<?xml version="1.0" encoding="UTF-8"?>
02
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
03
  <display-name>SpringTask</display-name>
04
  <context-param>
05
    <param-name>contextConfigLocation</param-name>
06
    <param-value>classpath*:config/spring/applicationContext.xml,classpath*:config/spring/applicationContext-quartz.xml</param-value>
07
  </context-param>
08
  <listener>
09
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
10
  </listener>
11
  <listener>
12
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
13
  </listener>
14
  <welcome-file-list>
15
    <welcome-file>index.html</welcome-file>
16
    <welcome-file>index.htm</welcome-file>
17
    <welcome-file>index.jsp</welcome-file>
18
    <welcome-file>default.html</welcome-file>
19
    <welcome-file>default.htm</welcome-file>
20
    <welcome-file>default.jsp</welcome-file>
21
  </welcome-file-list>
22
</web-app>
Spring的配置文件[這裡主要配置了Spring的注解、任務]:

01
<?xml version="1.0" encoding="UTF-8"?>
02
<beans xmlns="http://www.springframework.org/schema/beans"
03
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04
     xmlns:jaxws="http://cxf.apache.org/jaxws"
05
     xmlns:aop="http://www.springframework.org/schema/aop"
06
     xmlns:tx="http://www.springframework.org/schema/tx"
07
     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
08
     xmlns:context="http://www.springframework.org/schema/context"
09
     xsi:schemaLocation="
10
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
11
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
12
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
13
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
14
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
15
     http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
16
 
17
    <!-- enable autowire -->
18
    <context:annotation-config />
19
 
20
    <!--自動掃描base-package下面的所有的java類,看看是否配置了annotation -->
21
    <context:component-scan base-package="com.jing.spring" />
22
 
23
    <!-- enable transaction demarcation with annotations -->
24
    <tx:annotation-driven />
25
 
26
    <!-- 定時任務的配置 -->
27
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false">
28
        <property name="triggers">
29
            <list>
30
            </list>
31
        </property>
32
    </bean>
33
</beans>
java文件:
Task.java[達到任務調用時執行的類]:

01
package com.jing.spring.scheduler.task;
02
 
03
import org.apache.log4j.Logger;
04
import org.springframework.stereotype.Component;
05
 
06
/**
07
 * 定時任務類
08
 * <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a>  jing.yue
09
 * @version 2012/07/24 1.0.0
10
 */
11
@Component
12
public class Task extends TaskAbs {
13
 
14
    // log4j日志
15
    private static final Logger logger = Logger.getLogger(Task.class);
16
 
17
    /**
18
     * 調用定時任務
19
     * @param taskId
20
     * @param taskType
21
     */
22
    @Override
23
    public void startTask(String taskId, String taskType) {
24
        // TODO Auto-generated method stub
25
        try {
26
            logger.info("執行TaskJob任務...");
27
            logger.info("任務編號: " + taskId + "\t任務類型: " + taskType);
28
            logger.info("在這裡加入您需要操作的內容...");
29
        } catch (Exception e) {
30
            logger.info("發送微博的定時任務類--出錯");
31
            logger.info(e,e);
32
        }
33
    }
34
}
TaskAbs.java[任務調用的抽象類]:
01
package com.jing.spring.scheduler.task;
02
 
03
/**
04
 * 定時任務抽象類
05
 * <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a>  jing.yue
06
 * @version 2012/07/24 1.0.0
07
 */
08
public abstract class TaskAbs {
09
 
10
    /** 任務前綴 */
11
    public final static String TASK_FIRST = "cron_";
12
 
13
    /** 任務ID */
14
    public final static String TASK_ID = "taskId";
15
 
16
    /** 任務類型 */
17
    public final static String TASK_TYPE = "taskType";
18
 
19
    /** 任務 */
20
    public static final String TASK = "task";
21
 
22
    /** 默認的任務過期時間[單位為毫秒] */
23
    public static final long DEFAULT_PAST_TIME = 0;
24
 
25
    /**
26
     * 調用定時任務
27
     * @param taskId
28
     * @param taskType
29
     */
30
    public abstract void startTask(String taskId, String taskType);
31
 
32
}
TaskJob.java[達到任務調用時的入口]:
01
package com.jing.spring.scheduler.task;
02
 
03
import org.quartz.JobExecutionContext;
04
import org.quartz.JobExecutionException;
05
import org.springframework.scheduling.quartz.QuartzJobBean;
06
 
07
/**
08
 * 定時任務Job
09
 * <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a>  jing.yue
10
 * @version 2012/07/24 1.0.0
11
 */
12
public class TaskJob extends QuartzJobBean {
13
 
14
    //任務類
15
    private Task task;
16
 
17
    /**
18
     * 達到調用定時任務時, 系統會自動調用該方法
19
     */
20
    @Override
21
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
22
        // TODO Auto-generated method stub
23
        String taskId = (String) jobExecutionContext.getJobDetail().getJobDataMap().get(TaskAbs.TASK_ID);
24
        String taskType = (String) jobExecutionContext.getJobDetail().getJobDataMap().get(TaskAbs.TASK_TYPE);
25
        task.startTask(taskId, taskType);
26
    }
27
 
28
    public Task getTask() {
29
        return task;
30
    }
31
 
32
    public void setTask(Task task) {
33
        this.task = task;
34
    }
35
 
36
}
TaskManager.java[添加和刪除任務的類]:
001
package com.jing.spring.scheduler.task;
002
 
003
import java.text.ParseException;
004
import java.text.SimpleDateFormat;
005
import java.util.Calendar;
006
import java.util.Date;
007
 
008
import org.apache.log4j.Logger;
009
import org.quartz.CronTrigger;
010
import org.quartz.JobDetail;
011
import org.quartz.Scheduler;
012
import org.quartz.SchedulerException;
013
import org.springframework.beans.factory.annotation.Autowired;
014
import org.springframework.stereotype.Component;
015
 
016
import com.jing.spring.scheduler.utils.CronExpConversion;
017
 
018
/**
019
 * 定時任務加載工具類
020
 * <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a>  jing.yue
021
 * @version 2012/07/24 1.0.0
022
 */
023
@Component
024
public class TaskManager {
025
 
026
    private static final Logger logger = Logger.getLogger(TaskManager.class);
027
 
028
    @Autowired
029
    private Scheduler scheduler;
030
    @Autowired
031
    private Task task;
032
 
033
    /**
034
     * 添加任務
035
     * @param date 定時日期 格式:"YYYY-MM-DD" 例:"2012-06-29"
036
     * @param hour 定時小時 格式:"HH" 例:"12"
037
     * @param minute 定時分鐘 格式:"mm" 例:"59"
038
     * @param second 定時秒 格式:"ss" 例:""
039
     * @param taskId 微博活動ID[為負數代表我的微博的任務]
040
     * @param taskType 活動類型[0:代表我的微博/1:代表活動微博]
041
     * <a href="http://my.oschina.net/u/556800" target="_blank" rel="nofollow">@return</a>  false:失敗 true:成功
042
     */
043
    public boolean addTask(String date, String hour, String minute, String second, String taskId, String taskType){
044
        // TODO Auto-generated method stub
045
        if(date == null || hour == null || minute == null || second == null || taskId == null){
046
            return false;
047
        }
048
 
049
        boolean type = false;
050
        try {
051
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
052
 
053
            Date taskDate = sdf.parse(date + " " + hour + ":" + minute + ":" + second);
054
            Date newDate = Calendar.getInstance().getTime();
055
 
056
            //任務過期加上默認延遲的時間, 則立刻執行
057
            if(taskDate.getTime() <= (newDate.getTime() + TaskAbs.DEFAULT_PAST_TIME) ) {
058
                task.startTask(taskId, taskType);
059
            }
060
 
061
            logger.info("加入任務編號: " + taskId + "\t加入任務類型: " + taskType);
062
 
063
            //得到調度的任務的String類型的格式[如: 0 0 12 29 6 ?]
064
            String cron = CronExpConversion.convertDateToCronExp("userDefined", new String[]{second, minute, hour}, null, null, date);
065
 
066
            //設置JobDetail的信息
067
            JobDetail jobDetail =new JobDetail();
068
            jobDetail.setName("job_" + taskType + taskId);
069
            jobDetail.getJobDataMap().put(TaskAbs.TASK, task);
070
            jobDetail.getJobDataMap().put(TaskAbs.TASK_ID, taskId);
071
            jobDetail.getJobDataMap().put(TaskAbs.TASK_TYPE, taskType);
072
            jobDetail.setJobClass(TaskJob.class);
073
            scheduler.addJob(jobDetail, true);
074
 
075
            //創建任務
076
            CronTrigger cronTrigger = new CronTrigger(TaskAbs.TASK_FIRST + taskType + taskId, Scheduler.DEFAULT_GROUP, jobDetail.getName(), Scheduler.DEFAULT_GROUP);
077
            cronTrigger.setCronExpression(cron);
078
 
079
            //設置任務
080
            scheduler.scheduleJob(cronTrigger);
081
            type = true;
082
        } catch (ParseException e) {
083
            logger.info("添加任務--錯誤!");
084
            logger.info(e,e);
085
        } catch (SchedulerException e) {
086
            logger.info("添加任務--錯誤!");
087
            logger.info(e,e);
088
        }
089
 
090
        return type;
091
    }
092
 
093
    /**
094
     * 刪除任務
095
     * @param taskId 微博活動ID
096
     * @param taskType 活動類型[0:代表我的微博/1:代表活動微博]
097
     * <a href="http://my.oschina.net/u/556800" target="_blank" rel="nofollow">@return</a>  false:失敗 true:成功
098
     */
099
    public boolean cancelTask(Long taskId, String taskType){
100
        // TODO Auto-generated method stub
101
        if(taskId == null){
102
            return false;
103
        }
104
        logger.info("取消任務編號: " + taskId + "\t取消任務類型: " + taskType);
105
        boolean type = false;
106
        try {
107
            scheduler.unscheduleJob(TaskAbs.TASK_FIRST + taskType + taskId, Scheduler.DEFAULT_GROUP);
108
            type = true;
109
        } catch (SchedulerException e) {
110
            logger.info("刪除任務--錯誤!");
111
            logger.info(e,e);
112
        }
113
        return type;
114
    }
115
 
116
}
CronExpConversion.java:
01
package com.jing.spring.scheduler.utils;
02
 
03
/**
04
 * 時間任務處理類
05
 * <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a>  jing.yue
06
 * @version 2012/07/24 1.0.0
07
 */
08
public class CronExpConversion {
09
 
10
    /**
11
     * 頁面設置轉為UNIX cron expressions 轉換算法
12
     *  @param  everyWhat
13
     *  @param  commonNeeds 包括 second minute hour
14
     *  @param  monthlyNeeds 包括 第幾個星期 星期幾
15
     *  @param  weeklyNeeds  包括 星期幾
16
     *  @param  userDefinedNeeds  包括具體時間點
17
     *  <a href="http://my.oschina.net/u/556800" target="_blank" rel="nofollow">@return</a>   cron expression
18
     */
19
    public static String convertDateToCronExp(String everyWhat, String[] commonNeeds, String[] monthlyNeeds, String weeklyNeeds, String userDefinedNeeds)  {
20
        // TODO Auto-generated method stub
21
        String cronEx = "" ;
22
        String commons = commonNeeds[ 0 ] + " " + commonNeeds[ 1 ] + " " + commonNeeds[ 2 ] +  " " ;
23
        String dayOfWeek = "";
24
        if  ("monthly".equals(everyWhat))  {
25
            //  eg.: 6#3 (day 6 = Friday and "#3" = the 3rd one in the
26
            //  month)
27
            dayOfWeek  =  monthlyNeeds[ 1 ]
28
                                        +  CronExRelated.specialCharacters
29
                                        .get(CronExRelated._THENTH)  +  monthlyNeeds[ 0 ];
30
            cronEx  =  (commons
31
                    +  CronExRelated.specialCharacters.get(CronExRelated._ANY)
32
                    +   "   "
33
                    +  CronExRelated.specialCharacters.get(CronExRelated._EVERY)
34
                    +   "   "   +  dayOfWeek  +   "   " ).trim();
35
        }   else   if  ( "weekly" .equals(everyWhat))  {
36
            dayOfWeek  =  weeklyNeeds;  //  1
37
            cronEx  =  (commons
38
                    +  CronExRelated.specialCharacters.get(CronExRelated._ANY)
39
                    +   "   "
40
                    +  CronExRelated.specialCharacters.get(CronExRelated._EVERY)
41
                    +   "   "   +  dayOfWeek  +   "   " ).trim();
42
        }   else   if  ( "userDefined" .equals(everyWhat))  {
43
            String dayOfMonth  =  userDefinedNeeds.split( "-" )[ 2 ];
44
            if  (dayOfMonth.startsWith( "0" ))  {
45
                dayOfMonth  =  dayOfMonth.replaceFirst( "0" ,  "" );
46
            }
47
            String month  =  userDefinedNeeds.split( "-" )[ 1 ];
48
            if  (month.startsWith( "0" ))  {
49
                month  =  month.replaceFirst( "0" , "" );
50
            }
51
            // FIXME 暫時不加年份 Quartz報錯
52
            //             String year  =  userDefinedNeeds.split( " - " )[ 0 ];
53
            /* cronEx = (commons + dayOfMonth + " " + month + " "
54
                       + CronExRelated.specialCharacters.get(CronExRelated._ANY)
55
                       + " " + year).trim(); */
56
            cronEx  =  (commons  +  dayOfMonth  +   " "   +  month  +   " "
57
                    +  CronExRelated.specialCharacters.get(CronExRelated._ANY)
58
                    +   " " ).trim();
59
        }
60
        return  cronEx;
61
    }
62
 
63
 
64
    public static void main(String[] args) {
65
        String cron = CronExpConversion.convertDateToCronExp("userDefined", new String[]{"0","0","12"}, null, null, "2012-06-29");
66
        System.out.println(cron);
67
    }
68
}
CronExRelated.java:
01
package com.jing.spring.scheduler.utils;
02
 
03
import java.util.HashMap;
04
import java.util.Map;
05
 
06
/**
07
 * Quartz時間規則常量類
08
 * <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a>  jing.yue
09
 * @version 2012/07/24 1.0.0
10
 */
11
public class CronExRelated {
12
 
13
    public static final String _EVERY = "every";
14
    public static final String _ANY = "any";
15
    public static final String _RANGES = "ranges";
16
    public static final String _INCREMENTS = "increments";
17
    public static final String _ADDITIONAL = "additional";
18
    public static final String _LAST = "last";
19
    public static final String _WEEKDAY = "weekday";
20
    public static final String _THENTH = "theNth";
21
    public static final String _CALENDAR = "calendar";
22
 
23
    public static final String _TYPE = "type";
24
 
25
    /**
26
     * 0 0 6 ? * 1#1 ? monthly
27
     * 0 0 6 ? * 1 ? weekly
28
     * 0 0 6 30 7 ? 2006 useDefined
29
     */
30
    static String[] headTitle = {"TYPE","SECONDS","MINUTES","HOURS","DAYOFMONTH","MONTH","DAYOFWEEK","YEAR"};
31
 
32
    /**
33
     * cron expression special characters
34
     * Map
35
     * specialCharacters
36
     */
37
    public static Map<String,Object> specialCharacters;
38
 
39
    static {
40
        specialCharacters = new HashMap<String,Object>(10);
41
        specialCharacters.put(_EVERY, "*");
42
        specialCharacters.put(_ANY, "?");
43
        specialCharacters.put(_RANGES, "-");
44
        specialCharacters.put(_INCREMENTS, "/");
45
        specialCharacters.put(_ADDITIONAL, ",");
46
        specialCharacters.put(_LAST, "L");
47
        specialCharacters.put(_WEEKDAY, "W");
48
        specialCharacters.put(_THENTH, "#");
49
        specialCharacters.put(_CALENDAR, "C");
50
 
51
        specialCharacters.put(_TYPE, headTitle);
52
    }
53
 
54
    public static void set(String ex, int index) {
55
        // TODO Auto-generated method stub
56
        ((String[])specialCharacters.get(_TYPE))[index] = ex;
57
    }
58
}
下面附上添加任務的jsp:
 
01
<%<a href="http://my.oschina.net/page" target="_blank" rel="nofollow">@page</a>  import="java.text.SimpleDateFormat"%>
02
<%<a href="http://my.oschina.net/page" target="_blank" rel="nofollow">@page</a>  import="org.springframework.web.context.support.WebApplicationContextUtils"%>
03
<%<a href="http://my.oschina.net/page" target="_blank" rel="nofollow">@page</a>  import="org.springframework.web.context.WebApplicationContext"%>
04
<%<a href="http://my.oschina.net/page" target="_blank" rel="nofollow">@page</a>  import="com.jing.spring.scheduler.task.TaskManager"%>
05
<%@ page language="java" contentType="text/html; charset=UTF-8"
06
    pageEncoding="UTF-8"%>
07
<!DOCTYPE html PUBLIC "-//W4C//DTD HTML 4.01 Transitional//EN" "http://www.w4.org/TR/html4/loose.dtd">
08
<html>
09
<head>
10
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11
<title>Insert title here</title>
12
</head>
13
<body>
14
打開index.jsp自動添加10個任務
15
<%
16
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
17
TaskManager taskManager = (TaskManager) wac.getBean("taskManager");
18
taskManager.addTask("2012-07-24", "15", "40", "00", "0", "test");
19
taskManager.addTask("2012-07-24", "15", "41", "00", "1", "test");
20
taskManager.addTask("2012-07-24", "15", "42", "00", "2", "test");
21
taskManager.addTask("2012-07-24", "15", "43", "00", "3", "test");
22
taskManager.addTask("2012-07-24", "15", "44", "00", "4", "test");
23
taskManager.addTask("2012-07-24", "15", "45", "00", "5", "test");
24
taskManager.addTask("2012-07-24", "15", "46", "00", "6", "test");
25
taskManager.addTask("2012-07-24", "15", "47", "00", "7", "test");
26
taskManager.addTask("2012-07-24", "15", "48", "00", "8", "test");
27
taskManager.addTask("2012-07-24", "15", "49", "00", "9", "test");
28
%>
29
</body>
30
</html>

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved