Making a program run for 5 minutes

前端 未结 5 2079
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 14:03

So I wanted to try out something for a bit with the Timer and TimerTask classes.

I was able to get a line of code to execute after 30 seconds elapsed. What I\'ve been t

5条回答
  •  攒了一身酷
    2021-01-26 14:17

    Java has provided a rich set of APIs in java.util.concurrent package to achieve such tasks. One of these APIs is ScheduledExecutorService. For example consider the code given below: This code will execute the Runnable task after every 30 seconds for upto 5 minutes:

    import java.util.concurrent.*;
    
    class Scheduler 
    {
        private final ScheduledExecutorService service;
        private final long period = 30;//Repeat interval
        public Scheduler()
        {
            service = Executors.newScheduledThreadPool(1);
        }
        public void startScheduler(Runnable runnable)
        {
            final ScheduledFuture handler = service.scheduleAtFixedRate(runnable,0,period,TimeUnit.SECONDS);//Will cause the task to execute after every 30 seconds
            Runnable cancel = new Runnable()
            {
                @Override
                public void run()
                {
                    handler.cancel(true);
                    System.out.println("5 minutes over...Task is cancelled : "+handler.isCancelled());
                }
            };
            service.schedule(cancel,5,TimeUnit.MINUTES);//Cancels the task after 5 minutes
        }
        public static void main(String st[])
        {
            Runnable task = new Runnable()//The task that you want to run
            {
                @Override
                public void run()
                {
                    System.out.println("I am a task");
                }
            };
            Scheduler sc = new Scheduler();
            sc.startScheduler(task);
        }
    }     
    

提交回复
热议问题