天天看點

spring中定時任務的多種實作

本文主要是記錄工作中所遇到的情況,并非教學!!! 

一、通過spring自帶的@Scheduled注解實作定時任務

1.更改ApplicationContext-mvc.xml/spring.xml 等配置檔案,如果不知道自己應該配置哪個檔案的話去web.xml中找到<servlet>标簽中的配置檔案去配置就行(因為我試過配置在<context-param>标簽下的ApplicationContext.xml裡面會報錯)

spring中定時任務的多種實作

檔案中需要更改的内容如下:

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

      
(2)xsi:schemaLocation中添加  (其中spring-task-3.1.xsd的版本可以更改看你的spring版本)具體參考下圖      
spring中定時任務的多種實作
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd

      
1 <beans xmlns="http://www.springframework.org/schema/beans"
 2        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3        xmlns:context="http://www.springframework.org/schema/context"
 4        xmlns:aop="http://www.springframework.org/schema/aop"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xmlns:task="http://www.springframework.org/schema/task"
 7        xsi:schemaLocation="http://www.springframework.org/schema/beans
 8     http://www.springframework.org/schema/beans/spring-beans.xsd
 9     http://www.springframework.org/schema/aop
10     http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
11     http://www.springframework.org/schema/context
12     http://www.springframework.org/schema/context/spring-context.xsd
13     http://www.springframework.org/schema/mvc 
14     http://www.springframework.org/schema/mvc/spring-mvc.xsd
15 http://www.springframework.org/schema/task
16 http://www.springframework.org/schema/task/spring-task-3.1.xsd">      

(3)添加 task标簽設定 ,可以詳細配置也可以直接預設

多的部分是對與線程池的設定,配置線程池後如果多個定時任務同時執行也沒問題,不配置的話spring預設是單線程模式

1 <!--形式一-->
2 <task:executor id="executor" pool-size="5" />
3 <task:scheduler id="scheduler" pool-size="10" />
4 <task:annotation-driven executor="executor" scheduler="scheduler" />
5 
6 
7 <!--形式二-->
8  <task:annotation-driven />      

(4)不要忘記配置你要執行的自動化程式所在的包的路徑,将該包的路徑加入掃描(按照自身實際情況配置)

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

2.建立你的定時任務程式

1 /**
 2  * @author 
 3  * @Time 2020-07-08 17:07
 4  */
 5 //必須添加注解交由spring管控才能生效
 6 @Component
 7 public class ScheduledDemo {
 8     //由于将整個類交由spring管控不必擔心@Autowired注解失效的情況
 9     @Autowired
10     private TestService testService;
11 
12     //有點缺點該注解隻支援6位參數的cron表達式不支援7位的
13     @Scheduled(cron = "0 0/1 * * * ? ")
14     public void aaa(){
15         //實作你需要的方法即可
16         testService.XXX();
17         System.out.println("哈哈哈哈");
18     }
19 
20 }          

二、通過quartz元件實作定時任務(有點問題按照網上的方法最後我也沒成功納入spring管理。。。)

1.通過官網下載下傳quartz ,下載下傳完成是下圖的壓縮包 解壓後相應目錄下有你需要的jar包,自行導入即可(其他的都是依賴jar包,最低情況隻需要導入quartz自身的兩個jar就行)

spring中定時任務的多種實作
spring中定時任務的多種實作

配置一下日志列印(依賴于log4j元件)

spring中定時任務的多種實作

 2.此處就不講quartz怎麼使用了,結合網上的分享,這裡提供一個工具類友善直接調用

1 /**
 2  * @author 
 3  * @Time 2020-07-06 17:00
 4  */
 5 public class SchedulerUtil {
 6     private static Logger logger = Logger.getLogger(SchedulerUtil.class);// log4j記錄日志
 7     /**
 8      * [簡單任務排程:每次執行間隔為多少毫秒,執行多少次] <br>
 9      * @param jobName 任務名字
10      * @param jobGroupName 任務組名字
11      * @param triggerName 觸發器名字
12      * @param triggerGroupName 觸發器組名字
13      * @param jobClass 任務類
14      * @param time 時間間隔
15      * @param count 執行幾次<br>
16      */
17     public static void handleSimpleTrigger(String jobName, String jobGroupName,
18                                            String triggerName, String triggerGroupName, Class jobClass,
19                                            int time, int count) {28         // 通過schedulerFactory擷取一個排程器
29         SchedulerFactory schedulerfactory = new StdSchedulerFactory();
30         Scheduler scheduler = null;
31         try {
32             // 通過schedulerFactory擷取一個排程器
33             scheduler = schedulerfactory.getScheduler();
34             // 建立jobDetail執行個體,綁定Job實作類
35             // 指明job的名稱,所在組的名稱,以及綁定job類
36             JobDetail job = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
37             // 定義排程觸發規則
38             //使用simpleTrigger規則
39             Trigger trigger=TriggerBuilder.newTrigger().withIdentity(triggerName,triggerGroupName)
40                     .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(time).withRepeatCount(count))
41                     .build();
42             // 把作業和觸發器注冊到任務排程中
43             scheduler.scheduleJob(job, trigger);
44             // 啟動排程
45             scheduler.start();
46         } catch (Exception e) {48             logger.error("執行"+jobName+"組"+jobName+"任務出現異常E:["+ e.getMessage() + "]");
49         }
50     }
51     /**
52      * [複雜任務排程:每天幾點幾分幾秒定時執行任務] <br>
53      * @param jobName 任務名字
54      * @param jobGroupName 任務組名字
55      * @param triggerName 觸發器名字
56      * @param triggerGroupName 觸發器組名字
57      * @param jobClass 任務類
58      * @param cron 觸發規則<br>
59      */
60     /**
61      *
62      *
63      */
64     public static void hadleCronTrigger(String jobName, String jobGroupName,
65                                         String triggerName, String triggerGroupName, Class jobClass,String cron) {73         // 通過schedulerFactory擷取一個排程器
74         SchedulerFactory schedulerfactory = new StdSchedulerFactory();
75         Scheduler scheduler = null;
76         try {
77             // 通過schedulerFactory擷取一個排程器
78             scheduler = schedulerfactory.getScheduler();
79             // 建立jobDetail執行個體,綁定Job實作類
80             // 指明job的名稱,所在組的名稱,以及綁定job類
81             JobDetail job = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
82             // 定義排程觸發規則
83             //使用cornTrigger規則  每天18點30分
84             Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName)
85                     .withSchedule(CronScheduleBuilder.cronSchedule(cron))
86                     .build();
87             // 把作業和觸發器注冊到任務排程中
88             scheduler.scheduleJob(job, trigger);
89             // 啟動排程
90             scheduler.start();
91         } catch (Exception e) {93             logger.error("執行" + jobName + "組" + jobName + "任務出現異常E:[" + e.getMessage() + "]");
94         }
95     }
96 }      

3.方式一  :建立自己的job類,然後通過@PostConstruct注解在項目啟動後調用(配合第二條使用)

/**
 * @author 
 * @Time 2020-07-06 17:40
 */
@DisallowConcurrentExecution //不允許job并發執行,防止重複調用,隻對于同一執行個體有效,不同jobDetails引用同一個job時不起作用
public class TPersonFollowUpJob implements Job {

    @Autowired
    private TestService testService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

//因為沒有被納入spring管理,是以這裡通過這個方法實作調用spring管理的元件讓該頁面的@Autowired 注解生效   SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        //自己要實作的方法
        testService.XXX();
        System.out.println("哈哈哈哈");
    }
}      

下面是調用方法

//該注解保證了該方法可以在程式啟動後自動調用執行一次    
@PostConstruct
    public void start(){
        //這裡使用我們前面定義好的工具類來調用我們的Job方法類,這裡的cron表達式支援最多7位參數    
        SchedulerUtil.hadleCronTrigger("任務名字", "任務組名字","觸發器名字", "觸發器組名字", TPersonFollowUpJob.class,"0 0/1 * * * ? *");
    }      

4.方式二  :直接通過spring的xml配置完成(在web.xml的<context-param>标簽下的ApplicationContext.xml中進行配置,别的位置會報錯),獨立使用

1 <!--定時器任務配置(開始) -->
 2     <!--配置JOB -->
 3     <!--TPersonFollowUpTasksService這個bean是為了指定你早已經寫好的為了定時執行的方法所在的實作類 -->
 4     <bean id="TPersonFollowUpTasksService" class="com.msunsoft.service.personMana.Impl.TPersonFollowUpTasksServiceImpl"></bean>
 5     <bean id="JobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
 6         <property name="targetObject">
 7             <ref bean="TPersonFollowUpTasksService" />
 8         </property>
 9         <property name="targetMethod">
10 <!--在這裡指定需要定時執行的方法名-->
11             <value>createFollowUpTasks</value>
12         </property>
13         <property name="concurrent">
14             <value>false</value>
15         </property>
16     </bean>
17     <!--配置Trigger -->
18     <bean id="deleteDataTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
19         <property name="jobDetail">
20             <ref bean="JobDetail" />
21         </property>
22         <property name="cronExpression">
23             <!-- 這裡支援7個參數的corn表達式  每個小時的每分鐘執行一次 -->
24             <value>0 0/1 * * * ? *</value>
25         </property>
26     </bean>
27     <!--配置Scheduler -->
28     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false" autowire="no">
29         <property name="triggers">
30             <list>
31                 <ref bean="deleteDataTrigger" />
32             </list>
33         </property>
34         <property name="autoStartup">
35             <value>true</value>
36         </property>
37     </bean>
38     <!--定時器任務配置(結束) -->      
上一篇: 第五次作業