首页 > 代码库 > lesson9:分布式定时任务

lesson9:分布式定时任务

     在实际的开发过程中,我们一定会遇到服务自有的定时任务,又因为现在的服务都是分布式的,但是对于定时任务,很多的业务场景下,还是只希望单台服务来执行,网上有很多分布式定时任务的框架,各位如感兴趣,可以自行去研究。本文采用非常简单的方式实现了分布式的定时任务,利用了zookeeper的节点的EPHEMERAL_SEQUENTIAL特性,适用范围:

    1.定时任务跟随服务本身一起管理,不想引入过于复杂的分布式定时任务服务框架

    2.已有分布式定时任务服务框架,但对于一些定时任务,服务本身对它进行管理更加方便

    3.定时任务不要求100%的准确调度

源码 参考:https://github.com/mantuliu/javaAdvance :

package com.mantu.advance;import java.util.List;import java.util.Timer;import java.util.TimerTask;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooKeeper;import org.apache.zookeeper.ZooDefs.Ids;/** * blog http://www.cnblogs.com/mantu/ * github https://github.com/mantuliu/ * @author mantu * */public class Lesson9DistributedTask {    public static String  zkNode="";    public static ZooKeeper zk=null;    public static void main( String[] args )    {        try {                zk = new ZooKeeper("127.0.0.1:2181", 3000,new Watcher() {                // 监控所有被触发的事件                    public void process(WatchedEvent event) {                                        }                });                //zk.create("/task","timer".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);                //zk.create("/task/timer","timer".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);                zkNode= zk.create("/task/timer/","1".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL).replaceAll("/task/timer/", "");        } catch (Exception e) {            e.printStackTrace();        }        Timer timer = new Timer();        timer.schedule(new MyTask(), 1000, 2000);    }}class MyTask extends TimerTask {    @Override    public void run() {        if(Lesson9DistributedTask.zk!=null){            try {                System.out.println(Lesson9DistributedTask.zkNode);                List<String> list = Lesson9DistributedTask.zk.getChildren("/task/timer", false);                String temp = null;                System.out.println(list);                for(String i : list){                    if(temp!=null){                        if(i.compareTo(temp)<0){                            temp=i;                        }                    }                    else {                        temp=i;                    }                }                if(temp.equals(Lesson9DistributedTask.zkNode)){                    System.out.println("timer1 excute");                }            } catch (KeeperException e) {                e.printStackTrace();                return;            } catch (InterruptedException e) {                e.printStackTrace();                return;            }        }    }}

  在生产的实际使用过程中,按此方法实现的分布式定时任务运行的过程中,没有出现任何问题,此demo只是一个简单版的实现,如果需要在生产环境使用,还需要对zk的客户端进行监控。

 

lesson9:分布式定时任务