简体   繁体   中英

How to perform a task and return a data every minute

I want to create a function that perform some task and return the list every minute. But for now with help of this and some other links i am able to print the result but not return it.The main reason being the return type of run method is void which is not changing to a list.

My code looks like:

 List<String> ignoreList=new ArrayList<>();
   Map<String,List<String>> deviceMap=new HashMap<>(); 
   List<String> newlyAddedUUIDList=new ArrayList<>(); 

    int MINUTES = 1; // The delay in minutes
    Timer timer = new Timer();
     timer.schedule(new TimerTask() {
        @Override
        public void run() { // Function runs every MINUTES minutes.
            // Run the code you want here
   String xSubjectToken=SecretIdRetreiver.getXSubjectToken();
   Map<String, List<String>> uuidInfo= SecretIdRetreiver.getUUIDList(xSubjectToken); // If the function you wanted was static
   System.out.println(uuidInfo);
   Set<String> uuidSetList=uuidInfo.keySet();
   for(String uuid: uuidSetList) {
       if(ignoreList.contains(uuid)) {
          System.out.println("UUid already in the ignore list"); 
       }else {
           if(!deviceMap.containsKey(uuid)) {
               Map<String,List<String>> resultOfSC1=SecretIdRetreiver.performStage1Config(xSubjectToken, uuid);
               System.out.println(resultOfSC1);
               if(resultOfSC1.containsKey("AddInIgnoreList")) {
                   List<String> result=resultOfSC1.get("AddInIgnoreList");
                   String uuidToBeIgnored=result.get(0);
                       ignoreList.add(uuidToBeIgnored);                    
               }else if(resultOfSC1.containsKey("Successful")) {
                   List<String> result=resultOfSC1.get("Successful");
                   System.out.println(result);
                   String deviceId=result.get(1);
//                 System.out.println(deviceId);
                   String[] deviceuUIdSplit=deviceId.split("\\.");
                   String duUID=deviceuUIdSplit[0];
                   System.out.println(duUID);
                   String serialNumber=result.get(0);
                   String secretNumber=result.get(2);
                   List<String> info=new ArrayList<>();
                   info.add(secretNumber);
                   info.add(serialNumber);
                   if(deviceMap.containsKey(duUID)) {

                   }else {
                       newlyAddedUUIDList.add(duUID);
                   }
                   deviceMap.put(duUID, info);

               }
           }else {
               System.out.println("Already Added in the Device list");
           }

       }

   }
   getNewAddedUUId(newlyAddedUUIDList);
//   System.out.println(newlyAddedUUIDList+"NewAdded UUIDs");
   newlyAddedUUIDList.clear();


        }


      }, 0, 1000 * 60 * MINUTES);

    public static List<String> getNewAddedUUId(List<String> newlyAdded) {
    // TODO Auto-generated method stub
    System.out.println(newlyAdded+"Newly Added UUIDs");
    return newlyAdded;

}

The main objective is this code should be placed inside a function that will return the resultant list every minute.

Here's the problem - a function only returns once per invocation - not multiple times (eg once per minute).

So either call your function once per minute.

Or shove the list in some member variable and every minute tell the 'caller' to go have a look at it.

But now we're getting close to a Listener pattern. So in a UI say we have a button. And we have multiple parts of the code which all want to be notified when the button is pushed - so we add those things which want to be notified as listeners to the button. Then when the event happens on the button we can traverse the list of listeners and tell them that the event has happened.

A slightly more sophisticated use of this pattern is with Actions:

https://docs.oracle.com/javase/tutorial/uiswing/misc/action.html

https://docs.oracle.com/javase/7/docs/api/javax/swing/Action.html

This is producer consumer scenario. Your task in time thread is producer and what you need is consumer in another thread consuming producer results. This can get you started:

    BlockingQueue<Object> results = new LinkedBlockingDeque<>();

    //your task (aka producer)
    Runnable task = ()->{
        Object result = //compute your result
        results.add(result);
    };
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);        
    executor.scheduleAtFixedRate(task,0, 1, TimeUnit.MINUTES);

    //consumer
    while(true) {
        Object result = results.take();
    }

Make your own custom task that extends the TimerTask. In its constructor add a list that suits your needs. Then in the run method just modify your list.

Example

public class MyTimerTask extends TimerTask {
    public MyTimerTask(List<MyObject> objects) {
        super();
        this.objects = objects;
    }
    private final List<MyObject> objects;

    @Override
     public void run() {
         // your logic
         objects.add(whatever);
     }

    public List<MyObject> getElements() {
         return objects;
    }
}

Note: check out Java's concurrency classes. There is only one List but there are many different kinds of Queues. The documentation a good place to start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM