ejb3.0定時執行任務

來源:互聯網
上載者:User
 

ejb3.0定時執行任務 ejb3提供了,定時執行某項任務的功能實現步驟:1 . 建立一個sessionbean 和對應的介面 這個沒什麼特殊,跟以往一樣2.  擷取一個sessionContext對象3 . 在sessionContext中get到TimerService4. 在TimeService中擷取到Timer對象,建立該對象時候第一個參數代表定時任務開始執行的時間(精確到毫秒),第二個參數代表建個多久,第三個為傳入的參數(這個參數在執行任務的時候可以取到)5.寫一個方法,名稱規則為public xxx(Timer timer)6. 用annotation Timeout修飾這個方法  代碼實現
package com.foshanshop.ejb3.timer;  public interface TimerService{    public void scheduleTimer( long milliseconds);}     package com.foshanshop.ejb3.timer;  import java.util.Date;  import javax.annotation.Resource; import javax.ejb.Remote; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.ejb.Timeout; import javax.ejb.Timer; @Stateless@Remote({TimerService. class}) public class TimerServiceBean implements TimerService{    intcount = 0;    public@Resource SessionContext sctx;        public void scheduleTimer( long milliseconds)    {                sctx.getTimerService().createTimer( new Date( new Date().getTime()+milliseconds),milliseconds,"我的第一個定時器");        System. out.println("begin");     }    @Timeout    public void timeoutHandler(Timer time)    {        System. out.println("定時器發生"+time.getInfo());        count++;        if(count>5)            time.cancel();    }    public SessionContext getSctx()    {        returnsctx;    }     public void setSctx(SessionContext sctx)    {        this.sctx = sctx;    } }   執行結果11:03:15,750 INFO [STDOUT] begin11:03:16,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:17,765 INFO [STDOUT] 定時器發生我的第一個定時器11:03:18,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:19,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:20,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:21,750 INFO [STDOUT] 定時器發生我的第一個定時器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.