Java之旅--定時任務(Timer、Quartz、Spring、LinuxCron)

來源:互聯網
上載者:User

標籤:5.x   操作   usr   exception   encoding   exe   run   pac   txt   


在Java中,實現定時任務有多種方式。本文介紹4種。Timer和TimerTask、Spring、QuartZ、Linux Cron。

以上4種實現定時任務的方式。Timer是最簡單的。不須要不論什麼架構,只JDK就能夠。缺點是不過個時間間隔的定時器,調度簡單。Spring和QuartZ都支援cron,功能都非常強大,Spring的長處是略微簡單一點,QuartZ的長處是沒有Spring也可使用;Linux Cron是個作業系統層級的定時任務。適用於全部作業系統支援的語言,缺點是精度只能到達分鐘層級。


Timer和TimerTask


關於Timer定時器的實現原理,假設我們看過JDK原始碼,就會發現,是使用的Object.wait(timeout)。來進行的線程堵塞,timeout是依據下次運行實際和當前實際之差來計算。實際上,這能夠歸結為一個多線程協作(協作都是在相互排斥下的協作)問題。

在java.util.concurrent中。有個ScheduledThreadPoolExecutor。也能夠全然實現定時任務的功能。

而其它的架構,無非是功能的增強,特性很多其它,更好用,都是在基礎的java之上的封裝。

代碼示比例如以下:

import java.util.Date;  import java.util.Timer;  import java.util.TimerTask;   public class TimerTest extends TimerTask  {      private Timer timer;           public static void main(String[] args)      {          TimerTest timerTest= new TimerTest();          timerTest.timer = new Timer();                    //立馬開始運行timerTest任務,僅僅運行一次          timerTest.timer.schedule(timerTest,new Date());                    //立馬開始運行timerTest任務,運行完本次任務後。隔2秒再運行一次          //timerTest.timer.schedule(timerTest,new Date(),2000);                    //一秒鐘後開始運行timerTest任務。僅僅運行一次          //timerTest.timer.schedule(timerTest,1000);                    //一秒鐘後開始運行timerTest任務,運行完本次任務後,隔2秒再運行一次          //timerTest.timer.schedule(timerTest,1000,2000);                    //立馬開始運行timerTest任務,每隔2秒運行一次          //timerTest.timer.scheduleAtFixedRate(timerTest,new Date(),2000);                   //一秒鐘後開始運行timerTest任務。每隔2秒運行一次          //timerTest.timer.scheduleAtFixedRate(timerTest,1000,2000);          try          {              Thread.sleep(10000);          } catch (InterruptedException e)          {              e.printStackTrace();          }        //結束任務運行,程式終止          timerTest.timer.cancel();          //結束任務運行。程式並不終止,由於線程是JVM層級的          //timerTest.cancel();      }        @Override      public void run()      {          System.out.println("Task is running!");      }  } 


使用spring @Scheduled註解運行定時任務

這樣的方式很easy,卻能使用cron完畢和QuartZ一樣的功能,值得推薦一下。


ApplicationContext.xml:


beans根節點新增內容:xmlns:task="http://www.springframework.org/schema/task"

beans根節點中,xsi:schemaLocation屬性下添加:

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd

<!-- 開啟註解任務 -->

<task:annotation-driven/>

實作類別:

@Component  //import org.springframework.stereotype.Component;  public class MyTestServiceImpl  implements IMyTestService {        @Scheduled(cron="0/5 * *  * * ? ")   //每5秒運行一次        @Override        public void myTest(){              System.out.println("進入測試");        }  }


注意幾點:


spring的@Scheduled註解  須要寫在實現上;

定時器的任務方法不能有傳回值;

實作類別上要有組件的註解@Component。@Service。@Repository


QuartZ


QuartZ With Spring


applicationContext-schedule.xml


<?

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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <!-- 啟動的Trigger列表 --> <ref local="startThriftTrigger" /> </list> </property> <property name="quartzProperties"> <props> <prop key="org.quartz.threadPool.threadCount">5</prop> </props> </property> <!-- 啟動時延期3秒開始任務 --> <property name="startupDelay" value="3" /> <property name="autoStartup" value="${scheduler.autoStartup}" /> </bean> <!-- 啟動Thrift,馬上啟動 --> <bean id="startThriftTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="startDelay" value="0" /> <property name="repeatInterval" value="1000" /> <property name="repeatCount" value="0" /> <property name="jobDetail" ref="startThriftTask" /> </bean> <bean id="startThriftTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="startThrift" /> <property name="targetMethod" value="execute" /> <!-- 同一任務在前一次運行未完畢而Trigger時間又到時是否並發開始新的運行, 默覺得true. --> <property name="concurrent" value="true" /> </bean></beans>


實作類別


package xx.schedule;@Componentpublic class StartThrift { /**  * 調度入口  */ public void execute() {  // to do something } }


QuartZ No Spring


使用的QuartZ jar是1.8.5,例如以下:

<dependency>    <groupId>org.quartz-scheduler</groupId>    <artifactId>quartz</artifactId>    <version>1.8.5</version></dependency>


調用類實現代碼例如以下:

import org.quartz.CronExpression;import org.quartz.CronTrigger;import org.quartz.JobDetail;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.SchedulerFactory;import org.quartz.impl.StdSchedulerFactory;public class InvokeStatSchedule {       public void start() throws SchedulerException    {        SchedulerFactory schedulerFactory = new StdSchedulerFactory();        Scheduler scheduler = schedulerFactory.getScheduler();        //InvokeStatJob是實現了org.quartz.Job的類        JobDetail jobDetail = new JobDetail("jobDetail", "jobDetailGroup", InvokeStatJob.class);        CronTrigger cronTrigger = new CronTrigger("cronTrigger", "triggerGroup");        try {            CronExpression cexp = new CronExpression("0 0 * * * ?

"); cronTrigger.setCronExpression(cexp); } catch (Exception e) { e.printStackTrace(); } scheduler.scheduleJob(jobDetail, cronTrigger); scheduler.start(); } }


定時任務類代碼例如以下:

import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;public class InvokeStatJob implements Job {    @Override    public void execute(JobExecutionContext arg0) throws JobExecutionException {        //...要定時操作的內容       }}


Linux Cron


這事實上也是一種很普遍的實現定時任務的方式。實際是作業系統的定時任務。Linux Cron僅僅能到達分鐘級,到不了秒層級。

一般我們是設定定時運行一個sh指令碼,在指令碼裡面寫一些控制碼。比如,有例如以下的指令碼:

3,33 * * * * /usr/local/log_parser/run_log_parser.sh &


run_log_parser.sh的內容大致例如以下:


#!/bin/shlog_parser_dir=/usr/local/log_parsertmp_file=/usr/local/run_parser_tmp.txtparser_log=/usr/local/access_parser.logtmpDir=/data/applogs/access_logs_bpdate >> "$parser_log"if [! -f "$tmp_file"]; then        echo ‘訪問日誌解析進行中,尚未完畢‘ >> "$parser_log"        echo ‘‘ >> "$parser_log"else        echo ‘開始解析訪問日誌‘ >> "$parser_log"        touch "$tmp_file"        cd "$log_parser_dir"        python access_log_parser.py >> "$parser_log"        rm "$tmp_file"        echo ‘解析訪問日誌完畢‘ >> "$parser_log"        echo ‘‘ >> "$parser_log"        cd "$tmpDir"        gzip gzip WEB0*        mv *.gz gz/        echo ‘壓縮備份日誌及移動到壓縮檔夾成功‘ >> "$parser_log"fi

Java之旅--定時任務(Timer、Quartz、Spring、LinuxCron)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.