简体   繁体   中英

Scheduling tasks in Java

I have written a code in Java, something like this:

....
while (conditionX) {
  //fetch m
  ....
  t = new Thread(new SomeRunnable(m));
  t.start();
  Thread.sleep(500);
}
....

class SomeRunnable implements Runnable {
  String msisdn;
  public SomeRunnable (String m) {
    msisdn = m;
  }
  @Override
  public void run() {
    do {
      //Statement block S uses msisdn, sets condition Y
      Thread.sleep(30000);    
    } while (conditionY);
  }
}

I am not comfortable with the number Thread.sleep() s I have used in the code. To avoid this I tried ScheduledExecutor etc, but couldn't really figure out a way to do what I want.
I need half a second delay before a new thread is started , and in the thread, there has to be a 30s delay before the statement block S is tried again .

Please help me with a better way to code this using proper classes.
I have only provided an idea of how my code's work flow is, if I've to provide more info, please let me know.

Thanks

You can implement a TimerTask and override run() . Then you can schedule the task periodically with:

Timer myTimer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 500L, 30000L);

When you want to cancel your task, you can do that by calling cancel()

If you are using Spring to configure your beans you can focus just on implementing your business logic and leverage Spring's hooks for managing the tasks, schedules, etc.

http://static.springsource.org/spring/docs/1.2.x/reference/scheduling.html

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