Search code examples
javamethodstimerschedulerrunnable

Schedule to run a method at periodic time´


I have to schedule a method to be executed when starting and periodically thereafter at intervals of 1 minute.

For that I have done this:

public void init(){
    loadConfig(); //method which needs to be executed periodically

    Timer scheduler = new Timer();
    scheduler.scheduleAtFixedRate(loadConfig(),60000,60000);
}

This is giving an error and it should since the first parameter of scheduleAtFixedRate is of type Runnable.

What I need advice on, is how to make my loadConfig method Runnable and still have it executed when I do loadConfig() before the scheduler starts.

As of now code structure is as follows:

public class name {
    public void init() {
        ...
    }
    ...
    public void loadConfig() {
        ...
    }
}

EDIT: This is what I have already tried

public void init(){
    loadConfig();

    Timer scheduler = new Timer();
    scheduler.scheduleAtFixedRate(task,60000,60000);
}

final Runnable task = new Runnable() {
    public void run() {
        try {
            loadConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};

Solution

  • Using the following syntax you can create a lambda expression, which will evaluate to an object of type Runnable. When the run method of that object is called the loadConfig method will get called.

    scheduler.scheduleAtFixedRate(() -> loadConfig(), 60, 60, TimeUnit.SECONDS);
    

    Lambda expressions is a new Java 8 feature.

    In this case it works like this: The arrow, ->, makes the expression into a lambda. () is the argument list, which is empty because there are no argument to the run method. The loadConfig() after the arrow is the body, which works the same way as a method body.

    Since scheduleAtFixedRate expects a Runnable as a parameter, that will be the target type of the expression and the lambda will become an object of that type.