Schedule periodic tasks in Java

In Java application, some tasks need to execute periodically. For example, in an imaginary web app, there are two components: SessionService and ConfigService. The former component maintains a session pool of client users, it should clear expired user sessions every half an hour. The later component concentre a lot of important and frequently used configurations, it should save these configurations every an hour.

 

As we know, java.util.Timer and java.util.TimeTask classes can be used for these jobs. However, Time and TimeTask are not flexible enough for scheduling and controlling. From Java 5.0, java.util.concurrent package was introduced for concurrent programming. In this package, ScheduledExecutorService can be used to execute periodic command, and ScheduledFuture can be used to cancel or check execution.

 

ScheduledExecutorService have are two handy methods for scheduling:

ScheduledFuture<?> scheduleAtFixedRate(Runnable command,

                                       long initialDelay,

                                       long period,

                                       TimeUnit unit)

ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,

                                          long initialDelay,

                                          long delay,

                                          TimeUnit unit)

Please see the jdk documentation for more details.

 

Here, I will use ScheduledExecutorService and some other utility classes in concurrent package to implement the web app mentioned above.

There are 5 java classes/interfaces:

Schedulable: an interface that represent to a periodic task.

SessionService: a clear expired session task, implement the Schedulable interface.

ConfigService: a save configurations task, implement the Schedulable interface.

Scheduler: the core class to schedule all registered shedulable tasks.

MyServer: the server program, show the usage of these classes.

 

List 1: Schedulable.java

/**

 * Schedulable: represent a periodic task.

 */

public interface Schedulable {

       long getPeriod(); //get the period between successive executions.

      

       void setPeriod(long period); //set the period between successive executions.

 

       void schedule(); //the execution logic.

}

 

Schedulable just needs to implement the execution logic. It doesn’t care about how to execute periodically, that is Scheduler’s job!

 

List 2: Scheduler.java

/**

 * Scheduler: the core class to schedule tasks.

 */

import java.util.List;

import java.util.ArrayList;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

 

public class Scheduler {

       List<Schedulable> schedulables; // registered Schedulable list.

       ScheduledExecutorService executorService; // the scheduler.

 

       public Scheduler(){

              schedulables=new ArrayList<Schedulable>();

       }

 

       public void addSchedulable(Schedulable s){

              schedulables.add(s);

       }

 

       public void removeSchedulable(Schedulable s){

              schedulables.remove(s);

       }

 

       public void start(){

              System.out.println("scheduler start./n");

 

              int sz=schedulables.size();

              //here, we use the utility class Executors to create a ScheduledExecutorService,

              //it returns an instance of ScheduledThreadPoolExecutor.

              //the thread pool size is same to the Schedulable list's size.

              executorService=Executors.newScheduledThreadPool(sz);

 

              for(Schedulable s : schedulables)

                     executeSchedulable(s);

       }

 

       private void executeSchedulable(final Schedulable s){

              long period=s.getPeriod();

              long delay=period; //for simple, set delay=period

              //the excution logic should run in a separate thread.

              final Runnable r=new Runnable(){

                     public void run(){

                            s.schedule();

                     }

              };

              //here is the final place to schedule periodically.

              executorService.scheduleAtFixedRate(r,delay,period,TimeUnit.SECONDS);

       }

}

 

List 3: SessionService.java

/**

 * SessionService: a concrete class that implement Schedulable interface.

 */

import java.util.Map;

import java.util.HashMap;

 

public class SessionService implements Schedulable {

       private Map<String,String> userSessionMap=new HashMap<String,String>();

 

       private long clearPeriod=3600;

 

       public long getPeriod(){

              return clearPeriod;

       }

 

       public void setPeriod(long period){

              this.clearPeriod=period;

       }

 

       public void schedule(){

              System.out.println("begin clearExpiredSession().");

              clearExpiredSession();

              System.out.println("clearExpiredSession() finished./n");

       }

 

       private void clearExpiredSession(){

              System.out.println("I am clearing expired sessions.");

       }

 

}

 

List 4: ConfigService.java

/**

 * ConfigService: a concrete class that implement Schedulable interface.

 */

import java.util.Properties;

 

public class ConfigService implements Schedulable{

       private Properties configurations=new Properties();

 

       private long savePeriod=1800;

 

       public long getPeriod(){

              return savePeriod;

       }

 

       public void setPeriod(long period){

              this.savePeriod=period;

       }

 

       public void schedule(){

              System.out.println("begin saveConfig().");

              saveConfig();

              System.out.println("saveConfig() finished./n");

       }

 

       private void saveConfig(){

              System.out.println("I am saving configurations.");

       }

}

 

List 5: MyServer.java

/**

 * MyServer: a sample class that show the usage of Schedulable & Scheduler.

 */

public class MyServer{

 

       public static void main(String[] args){

              Scheduler scheduler=new Scheduler();

             

              //create a Schedulable instance, register it to Scheduler.

              SessionService ss=new SessionService();

              ss.setPeriod(1800);

              scheduler.addSchedulable(ss);

             

              //create a Schedulable instance, register it to Scheduler.

ConfigService cs=new ConfigService();

              cs.setPeriod(3600);

              scheduler.addSchedulable(cs);

 

              scheduler.start();

       }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值