Вопрос

I am developing a java application which computes various mathematical functions. Here is the scenario, I have M runnable tasks (each for computing various problems, like one solves quadratic eqns, other solves exponential functions, something like that). These M runnables has to be executed for every N mins. These runnables can be executed sequentially not necessarily in parallel manner. I am not allowed to create more than one thread.

I can use ScheduledExecutorService for running the tasks periodically. As per Javadoc, Only one runnable can be used with ScheduledExecutorService. There are methods like invokeAll(...), which allows us to provide Collection of runnable, but these doesnt provide scheduling option.

On browsing through internet I found, using Thread.sleep() is not a good way to develop an application.

Any suggestions??

Это было полезно?

Решение

You can create ExecutorService that contains only one thread to run your jobs:

ExecutorService executorService = Executors.newSingleThreadExecutor();

When you submit several jobs to this service using invokeAll method it will run them sequentially using single Thread instance.

If you want to use ScheduledExecutorService to run your jobs every N minutes you can switch to

ScheduledExecutorService scheduledExecutorService = 
    Executors.newSingleThreadScheduledExecutor();

that will provide you with additional methods to better control your jobs.

As you can see invokeAll method is derived from ExecutorService, so it does not provide you scheduling options. Still this is just a shortcut and you can schedule multiple Runnable instances using regular loop:

for (Runnable job : allJobs) {
    scheduledExecutorService.scheduleAtFixedRate(job, 0L, N, TimeUnit.MINUTES);
}

Другие советы

If you create a multiple runnable class like the following, you can pass an instance of it to your scheduler and it will run all the runnables that you instantiated it with. The scheduler does the rest, this just sequentially runs the array of runnables.

public class MultipleRunnable implements Runnable
{
    private Runnable[] commands;
    public MultipleRunnable(Runnable[] commands)
    {
        this.commands = commands;
    }

    public void run()
    {
        for(int i = 0 ; i < commands.length ; i++)
        {
             commands[i].run();
        }
    }
}

Something like this to start it should work:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(
new MultipleRunnable(new Runnable[]{run1, run2, ..., runM}),
n, n, TimeUnit.MINUTES);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top