39 (guava包)AbstractScheduledService的使用

package com.da.tool.guava;

import com.google.common.util.concurrent.AbstractScheduledService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 */
public class SchedulerJob extends AbstractScheduledService {

    private List<String> list;

    private static Boolean isEnd = false;

    @Override
    protected void runOneIteration() throws Exception {
        System.out.println("Add element to list ..........");
        list.add("test");
        if(list.size()>10){
            System.out.println("ShutDown job ..........");
            isEnd = true;
            this.stopAndWait();
        }
    }

    @Override
    protected void startUp() throws Exception {
        System.out.println("Job start ..........");
        list = new ArrayList<>();
    }

    @Override
    protected void shutDown() throws Exception {
        System.out.println("Job end ..........");
    }

    @Override
    protected Scheduler scheduler() {
        return Scheduler.newFixedRateSchedule(0,1, TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        SchedulerJob schedulerJob =new SchedulerJob();
        try {
            schedulerJob.startAndWait();
        } catch (Exception e) {
            e.printStackTrace();
        }
        while(!isEnd){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.getStackTrace();
            }
        }
        System.exit(0);
    }
}

 

posted @ 2017-04-06 16:50  life_start  阅读(1241)  评论(0编辑  收藏  举报