?
Solved

How to run a method every hour

Posted on 2003-03-05
12
Medium Priority
?
326 Views
Last Modified: 2010-03-31
Hi

  I have a servlet running all the time. How could i
run a method say every hour from that servlet ?
(need to create some zip files)

Thanx alot
0
Comment
Question by:b3cf
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +1
12 Comments
 
LVL 1

Accepted Solution

by:
ykaganov earned 200 total points
ID: 8073959
class MyTimer extends Thread {
  static final long HOUR = 3600000L; // 60*60*1000
  ZipCreator _creator;

  public MyTimer(ZipCreator creator) {
    super();
    creator = _creator;
  }

  public void run() {
    while(true) {
      try {
        sleep(HOUR);
        _creator.createZipFiles();
      } catch (InterruptedException ex) {
        ex.printStackTrace();  // shouldn't happen
      }
    }
  }
}

Make sure that createZipFiles() is threadsafe (or you may just implement it inside MyTimer), and think through where you create MyTimer objects: by default, a new instance of Servlet is created for each web request, so if you create new MyTimer inside a servlet instance, you will have one MyTimer running for each servlet request...

Hope this helps,

- Eugene
0
 

Author Comment

by:b3cf
ID: 8074482
Thanx alot Eugene.

I have a quick question. So the thread will sleep only
after doProcess() is done ?
Since its doing zipping alot of files, it might take a
few minutes. (may be even 25 minutes)

Thanx again.

 public void run() {
          while(true) {

               try {
                   doProcess();
                   sleep(this.DELAY);
               }
               catch (InterruptedException ex) {
                      ex.printStackTrace();  // shouldn't happen
               }
          }
   }
0
 
LVL 92

Expert Comment

by:objects
ID: 8074953
Just use a Timer:

import java.util.Timer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class TimerServlet extends HttpServlet
{
   private static final HOUR = 60 * 60 * 1000;

   private Timer timer = new Timer(true);

   public void init()
   {
      timer.scheduleAtFixedRate(new MyTimerTask(), HOUR, HOUR);
   }

   public void destroy()
   {
      timer.cancel();
   }

   public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException
   {
   }
}


And create the task to run as a subclass of TimerTask:

import java.util.TimerTask;

public class MyTimerTask extends TimerTask
{
  public void run()
  {
     // do your task here
  }
}
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 1

Expert Comment

by:ykaganov
ID: 8075130
b3cf,

Yes, it will sleep only after doProcess() is done.

If you want to have (processTime + sleepTime) == DELAY instead, you could do something like this:

  long startTime = System.currentTimeMillis();
  doProcess();
  long endTime   = System.currentTimeMillis();

  long processTime = endTime - startTime;
  long sleepTime = this.DELAY - processTime;

  if(sleepTime > 0) {
    sleep(sleepTime);
  }
0
 
LVL 92

Expert Comment

by:objects
ID: 8075220
Why reinvent the wheel?
0
 
LVL 1

Expert Comment

by:ykaganov
ID: 8075360
hmm, because it's easy? :)

Yeah, objects is right (as always), java.util.Timer will do exactly what you need. The only caveat is that it requires jdk1.3 and up.

But my way you get to learn about threads a little ;)
0
 
LVL 2

Expert Comment

by:functionpointer
ID: 8077612
do beware. java.util.Timer just sucks. It;s single thread blocks for the entire run() method of every task it holds. It's queue has somewhat questionable task sorting. It is impossible to predict exactly what time anything will happen, since it runs late tasks ASAP instead of the time you may have thought.

You can use it safely for a very few quick and simple tasks, but be very careful trusting it to be a faithful workhorse without alot of babysitting.
0
 
LVL 92

Expert Comment

by:objects
ID: 8077680
> java.util.Timer just sucks

do u know of a better alternative?

> It;s single thread blocks for the entire run() method of every task it holds.

If this is an issue then just use a TimerTask that kicks off a new thread to run the 'real' thread.

> since it runs late tasks ASAP instead of the time you may have thought.

It is documented that tasks should complete quickly.
If you know a task takes a while and may impact on the scheduling on other tasks, then use method suggected above.

> You can use it safely for a very few quick and simple tasks

I disagree, as it is designed to schedule *many* quick tasks.

Of course if you use it for a job it is not designed then of course you will run into problems.



0
 
LVL 2

Expert Comment

by:functionpointer
ID: 8077806
> do u know of a better alternative?
One better alternative is to write your own timer that doesn't block. That way you dont have to kick off a new thread. The idea of Timer was to simplify this. Creating a new Thread yourself everytime you schedule a task is not 'simplifying' things.

> If you know a task takes a while and may impact on the scheduling on other tasks, then use method suggected above.
And when do you have just too many Timer objects, just because your tasks are lengthy? Worrying about the tasks is enough, no need to worry about what Timer it is in.

> I disagree, as it is designed to schedule *many* quick tasks
Rightly said, depending on your definition of *many* and *quick*. Not so many you kill yourself on it's blocks that synchronize the whole queue object.

I respect your defense of the Language, objects! You truly are a great evangelist for our cause.
I just don't like java.util.Timer. ;)

If b3cf needs this task to run at the top of every hour, Timer may let him down unless he has his Task spin off a new Thread.
0
 

Author Comment

by:b3cf
ID: 8079616
Thanx alot guys. Appreciate your help a lot.
0
 
LVL 92

Expert Comment

by:objects
ID: 8083851
functionpointer,

It really comes down to using the right class for the right job. If Timer class meets your needs then your better off using it rather having to write something yourself. But it is not suitable for all situations, and if it isn't then you should look to an alternative that matches your requirements.

:)
0
 
LVL 2

Expert Comment

by:functionpointer
ID: 8085046
my sentiments exactly.
0

Featured Post

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month14 days, 22 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question