How to Run a Job Periodically with ScheduledExecutorService in Java


In this example, we will write an example to run a task periodically with ScheduledExecutorService.

Source Code

package com.beginner.examples;

import java.util.concurrent.*;

public class ScheduledExample {

    public static void main(String[] args){
    	//use scheduleAtFixedRate to run a task periodically.
    	ScheduledExecutorService example = Executors.newSingleThreadScheduledExecutor();
    	example.scheduleAtFixedRate(
        		new Runnable() 
        		{
				    @Override
				    public void run() {
				        System.out.println(System.currentTimeMillis());
				    }
				}, 
				0, 2000, TimeUnit.MILLISECONDS);
    }
}

Output:

1561627646946
1561627648946
1561627650946
1561627652947
1561627654947
1561627656947
1561627658947
1561627660947
1561627662948
1561627664948
1561627666948
1561627668948
1561627670948
1561627672949
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments