之前在的公司有專門的任務調度框架,需要使用的時候引個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(); } } 以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答