samedi 18 janvier 2020

How to get a particular futureTask from a list of ScheduledFuture (ScheduledExecutorService) and update the time?

Below is the code implementation...where I need to schedule tasks at random interval and update the time of the particular tasks :

    class Task implements Callable<String> 
                {
                    private final String name;
                    public Task(String name) {
                        this.name = name;
                    }
                    @Override
                    public String call() throws Exception {
                        return "Task [" + name + "] executed on : " + LocalDateTime.now().toString();
                    }
                }
public class Main 
{
    public static void main(String[] args) throws InterruptedException 
    {
                 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);          
                 List<ScheduledFuture<String>> results = new ArrayList<ScheduledFuture<String>>();
                        for (int i = 1; i <= 5; i++) 
                        {
                            Task task = new Task("Task-" + i);
                            ScheduledFuture<String> result = executor.schedule(task, i*2, TimeUnit.SECONDS);
                            results.add(result);
                        }    
                        executor.shutdown();     
                        try { 
                            executor.awaitTermination(1, TimeUnit.DAYS);              
                            for(ScheduledFuture<String> result : results) {
                                System.out.println(result.get());
                            }      
                        } catch (Exception e) { 
                            e.printStackTrace(); 
                        }

Aucun commentaire:

Enregistrer un commentaire