tags:

views:

173

answers:

3

Hi , I want a particular piece code to be executed after 5 minutes. How can I do that using Java?

        out.println("<HTML>");
        out.println("<head>");
        //out.println("<frame>");
        out.println("<frameset rows=\"80%, *\" frameborder=\"0\" border=\"0\" framespacing=\"0\">");
       out.println("<frame src=\"DataCenterImage.html\" target=\"DisplayFrame\">"); 
       //out.println("Hai");
        out.println("<frame src= \"unlock.html\" target=\"DisplayFrame\">"); 
        out.println("</frameset>");
        out.println("</head>");
        out.println("</HTML>");

I want the above to be excuted after 15 minutes.

A: 

You could use:

Thread.sleep(900000);
execute code...

The sleep() method takes milliseconds as arguments, therefore the huge number for your 15 minutes.

boutta
u mean i need to have a class that extends httpservlet and implements runnable thread
No, with Thread.sleep you tell the current thread to wait for a given amount of time. You don't need to implement anything.
boutta
+3  A: 

In Java 1.5 and above you can use the java.util.concurrent package

ScheduledExecutorService scheduler = Executors.newSingleThreadedScheduledExecutor();
ScheduledFuture<?> f = scheduler.schedule(new Runnable() {
    public void run() {
        //Code to be executed here
    }
}, 15L, TimeUnit.MINUTES);

You can cancel the execution thus:

f.cancel(false);
oxbow_lakes
in the code where did u mention 15 minutes
Your question says "5 minutes". If it's 15 I'll edit the code
oxbow_lakes
I agree that Quartz is overkill. That is why I voted +1 on your answer. I still gave my answer for completeness
Nicolai
+1  A: 

The Quartz framework may also be helpful to you.

From their site:

Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

I have used this a lot for scheduling in different type of applications and have been very happy with it.

Nicolai
Using Quartz is a bit heavy-handed for the answer to "I want to execute X in 5 minutes". I would only consider Quartz if I wanted cron-like execution, missed triggers, stateful execution etc etc
oxbow_lakes