国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java Web項目中編寫定時任務的實現

2019-11-26 13:10:52
字體:
來源:轉載
供稿:網友

之前在的公司有專門的任務調度框架,需要使用的時候引個jar包加個配置和注解就可以使用了,還有專門的平臺來維護運行的機器及監(jiān)控執(zhí)行狀態(tài)等等。

現在突然沒了這個工具,而又要寫定時任務,該怎么辦呢?

對于非Web應用來說,我們可以使用Quartz,使用簡單,功能強大。

對于Java Web應用來說,當然也可以使用Quartz(有一篇介紹了方法://m.survivalescaperooms.com/article/104105.htm),但是還有更方便的工具,那就是spring自帶的支持定時任務功能。

Spring的定時任務在spring-context中,簡單配置的模板如下:

<?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í)行定時任務使用的scheduler,默認使用的是

org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

task:annotation-driven允許使用@Async和@Scheduled注解;

task:scheduler-tasks中定義了一個個task,其中執(zhí)行周期可以使用cron表達式,還可指定延時或頻率等方式。

有一個轉換cron的在線工具挺好用,推薦給大家(注意這里可能會顯示7個字符,去掉最后一個*即可):http://tools.VeVB.COm/code/Quartz_Cron_create

接下來還有一個問題,通常我們的線上環(huán)境是集群環(huán)境,有多臺機器,而這些定時任務通常只需要在一臺上執(zhí)行,如何來進行控制呢?

目前想到兩種辦法,分享給大家:

1. 使用Redis全局緩存

//m.survivalescaperooms.com/article/104111.htm

2. 通過判斷文件的方式

通過判斷某文件是否存在,來決定是否執(zhí)行任務(是否加載任務對應的spring配置文件),參考代碼:

@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) {    // 類已加載過    return;   }    Resource resource = applicationContext.getResource("classpath:<標識文件>");   if (!resource.exists()) {    // 文件不存在,不啟動    return;   }      ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(applicationContext);   context.setConfigLocations("classpath:spring/job.xml");   context.refresh();  } } 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 新郑市| 定陶县| 南乐县| 西青区| 乌兰浩特市| 万源市| 开原市| 桃江县| 肥城市| 灵石县| 攀枝花市| 福州市| 崇仁县| 林州市| 淮安市| 墨脱县| 新乡县| 安达市| 宜宾县| 榆社县| 霞浦县| 筠连县| 巫溪县| 台中县| 石林| 汉川市| 榆林市| 九龙城区| 乳源| 都江堰市| 来凤县| 平泉县| 南宫市| 西藏| 高要市| 邢台县| 时尚| 永登县| 江孜县| 周至县| 通许县|