之前在的公司有專(zhuān)門(mén)的任務(wù)調(diào)度框架,需要使用的時(shí)候引個(gè)jar包加個(gè)配置和注解就可以使用了,還有專(zhuān)門(mén)的平臺(tái)來(lái)維護(hù)運(yùn)行的機(jī)器及監(jiān)控執(zhí)行狀態(tài)等等。
現(xiàn)在突然沒(méi)了這個(gè)工具,而又要寫(xiě)定時(shí)任務(wù),該怎么辦呢?
對(duì)于非Web應(yīng)用來(lái)說(shuō),我們可以使用Quartz,使用簡(jiǎn)單,功能強(qiáng)大。
對(duì)于Java Web應(yīng)用來(lái)說(shuō),當(dāng)然也可以使用Quartz(有一篇介紹了方法:http://m.ythuaji.com.cn/article/90551.html),但是還有更方便的工具,那就是spring自帶的支持定時(shí)任務(wù)功能。
Spring的定時(shí)任務(wù)在spring-context中,簡(jiǎn)單配置的模板如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<? 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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> < task:scheduler id = "scheduler" pool-size = "200" /> < task:scheduled-tasks > <!-- 你的task --> < task:scheduled ref = "xxxTask" method = "execute" cron = "0 0 * * * ?" /> </ task:scheduled-tasks > < task:annotation-driven scheduler = "scheduler" /> </ beans > |
其中task:scheduler指定了執(zhí)行定時(shí)任務(wù)使用的scheduler,默認(rèn)使用的是
org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
task:annotation-driven允許使用@Async和@Scheduled注解;
task:scheduler-tasks中定義了一個(gè)個(gè)task,其中執(zhí)行周期可以使用cron表達(dá)式,還可指定延時(shí)或頻率等方式。
接下來(lái)還有一個(gè)問(wèn)題,通常我們的線上環(huán)境是集群環(huán)境,有多臺(tái)機(jī)器,而這些定時(shí)任務(wù)通常只需要在一臺(tái)上執(zhí)行,如何來(lái)進(jìn)行控制呢?
目前想到兩種辦法,分享給大家:
1. 使用Redis全局緩存
http://m.ythuaji.com.cn/article/25666.html
2. 通過(guò)判斷文件的方式
通過(guò)判斷某文件是否存在,來(lái)決定是否執(zhí)行任務(wù)(是否加載任務(wù)對(duì)應(yīng)的spring配置文件),參考代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@Component public class XxxListener implements ApplicationContextAware { // 防止加載多次 private static final AtomicInteger INIT_LOCK = new AtomicInteger( 0 ); @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (INIT_LOCK.incrementAndGet() > 1 ) { // 類(lèi)已加載過(guò) return ; } Resource resource = applicationContext.getResource( "classpath:<標(biāo)識(shí)文件>" ); if (!resource.exists()) { // 文件不存在,不啟動(dòng) return ; } ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(applicationContext); context.setConfigLocations( "classpath:spring/job.xml" ); context.refresh(); } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/mj158518/article/details/54694589